Thread详解

1.创建多线程的两种方式:

    1.1 继承Thread方法

class PrintNum extends Thread{
	public void run(){
		//子线程执行的代码
		for(int i = 1;i <= 100;i++){
			if(i % 2 == 0){
				System.out.println(Thread.currentThread().getName() + ":" + i);
			}
		}
	}
	public PrintNum(String name){
		super(name);
	}
}


public class TestThread {
	public static void main(String[] args) {
		PrintNum p1 = new PrintNum("线程1");
		PrintNum p2 = new PrintNum("线程2");
		p1.setPriority(Thread.MAX_PRIORITY);//10
		p2.setPriority(Thread.MIN_PRIORITY);//1
		p1.start();
		p2.start();
	}
}

 

    1.2 实现Runnable接口

//1.创建一个实现了Runnable接口的类
class PrintNum1 implements Runnable {
	//2.实现接口的抽象方法
	public void run() {
		// 子线程执行的代码
		for (int i = 1; i <= 100; i++) {
			if (i % 2 == 0) {
				System.out.println(Thread.currentThread().getName() + ":" + i);
			}
		}
	}
}

public class TestThread1 {
	public static void main(String[] args) {
		//3.创建一个Runnable接口实现类的对象
		PrintNum1 p = new PrintNum1();
//		p.start();
//		p.run();
		//要想启动一个多线程,必须调用start()
		//4.将此对象作为形参传递给Thread类的构造器中,创建Thread类的对象,此对象即为一个线程
		Thread t1 = new Thread(p);
		//5.调用start()方法:启动线程并执行run()
		t1.start();//启动线程;执行Thread对象生成时构造器形参的对象的run()方法。
		
		//再创建一个线程
		Thread t2 = new Thread(p);
		t2.start();
	}
}

两种方式对比:实现的方式优于继承的方式
                           ① 避免了java单继承的局限性;
                           ② 如果多个线程要操作同一份资源(或数据),更适合使用实现的方式。

2.线程的常用方法:

 2.1.start():启动线程并执行相应的run方法;
 2.2.run():子线程要执行的代码放入run()方法中;
 2. 3.currentThread():静态的,调取当前线程;
 2.4.getName():获取次线程的名字;
 2.5.setName():设置此线程的名字。
 2. 6.yield():调用此方法的线程释放当前CPU的执行权;
 2.7.join():在A线程中调用B线程的join()方法,表示:当执行到此方法,A线程停止执行,直到B线程执行完毕,
      A线程再接着join()之后的代码执行;
 2.8.isAlive():判断当前线程是否存活。
 2.9.sleep(long 1):显示的让当前线程睡眠1毫秒;
 2.10.线程通信 Object中的wait();notify();notifyAll()三个方法;
 2.11.设置线程的优先级

3.synchronized字段

  3.1.线程安全问题存在的原因?
    由于一个线程在操作共享数据过程中,未执行完毕的情况下,另外的线程参与进来,导致共享数据存在了安全问题。
    
  3.2.如何来解决线程的安全问题?
      必须让一个线程操作共享数据完毕以后,其它线程才有机会参与共享数据的操作。
  
  3.3.java如何实现线程的安全:线程的同步机制
         
         方式一:同步代码块
        synchronized(同步监视器){
             //需要被同步的代码块(即为操作共享数据的代码)
         }
          1.共享数据:多个线程共同操作的同一个数据(变量)
          2.同步监视器:由一个类的对象来充当。哪个线程获取此监视器,谁就执行大括号里被同步的代码。俗称:锁
             要求:所有的线程必须共用同一把锁!
             注:在实现的方式中,考虑同步的话,可以使用this来充当锁。但是在继承的方式中,慎用this!
 
      方式二:同步方法
        将操作共享数据的方法声明为synchronized。即此方法为同步方法,能够保证当其中一个线程执行
        此方法时,其它线程在外等待直至此线程执行完此方法。
        >同步方法的锁:this

     3.4.线程的同步的弊端:由于同一个时间只能有一个线程访问共享数据,效率变低了。

      方式1:同步代码块

class Window3 extends Thread {
	static int ticket = 100;
	static Object obj = new Object();

	public void run() {
		while (true) {
			// synchronized (this) {//在本问题中,this表示:w1,w2,w3
			synchronized (obj) {
				// show();
				if (ticket > 0) {
					try {
						Thread.currentThread().sleep(10);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName()
							+ "售票,票号为:" + ticket--);
				}
			}
		}
	}

	public synchronized void show() {// this充当的锁
		if (ticket > 0) {
			try {
				Thread.currentThread().sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "售票,票号为:"
					+ ticket--);
		}
	}
}

public class TestWindow3 {
	public static void main(String[] args) {
		Window3 w1 = new Window3();
		Window3 w2 = new Window3();
		Window3 w3 = new Window3();

		w1.setName("窗口1");
		w2.setName("窗口2");
		w3.setName("窗口3");

		w1.start();
		w2.start();
		w3.start();

	}

}

方式2:同步方法

class Window4 implements Runnable {
	int ticket = 100;// 共享数据

	public void run() {
		while (true) {
			show();
		}
	}

	public synchronized void show() {
		
		if (ticket > 0) {
			try {
				Thread.currentThread().sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "售票,票号为:"
					+ ticket--);
		}

	}
}

public class TestWindow4 {
	public static void main(String[] args) {
		Window4 w = new Window4();
		Thread t1 = new Thread(w);
		Thread t2 = new Thread(w);
		Thread t3 = new Thread(w);

		t1.setName("窗口1");
		t2.setName("窗口2");
		t3.setName("窗口3");

		t1.start();
		t2.start();
		t3.start();
	}
}

4.死锁
死锁的问题:处理线程同步时容易出现。
不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁
写代码时,要避免死锁!

demo:将代码中的两个线程的sleep()取消注释,则出现死锁问题;

public class TestDeadLock {

	static StringBuffer sb1 = new StringBuffer();
	static StringBuffer sb2 = new StringBuffer();

	public static void main(String[] args) {
		new Thread() {
			public void run() {
				synchronized (sb1) {
					try {
					//	Thread.currentThread().sleep(10); 
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					sb1.append("A");
					synchronized (sb2) {
						sb2.append("B");
						System.out.println(sb1);
						System.out.println(sb2);
					}
				}
			}
		}.start();

		new Thread() {
			public void run() {
				synchronized (sb2) {
					try {
						//Thread.currentThread().sleep(10);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					sb1.append("C");
					synchronized (sb1) {
						sb2.append("D");
						System.out.println(sb1);
						System.out.println(sb2);
					}
				}
			}
		}.start();
	}

}

5.线程的通信:如下的三个关键字使用的话,都得在同步代码块或同步方法中。
wait():一旦一个线程执行到wait(),就释放当前的锁。
notify()/notifyAll():唤醒wait的一个或所有的线程
使用两个线程打印 1-100. 线程1, 线程2 交替打印。

class PrintNum implements Runnable {
	int num = 1;
	Object obj = new Object();
	public void run() {
		while (true) {
			synchronized (obj) {
				obj.notify();
				if (num <= 100) {
					try {
						Thread.currentThread().sleep(10);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + ":"
							+ num);
					num++;
				} else {
					break;
				}
				
				try {
					obj.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}

public class TestCommunication {
	public static void main(String[] args) {
		PrintNum p = new PrintNum();
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(p);
		
		t1.setName("甲");
		t2.setName("乙");
		
		t1.start();
		t2.start();
	}
}

6.总结案例:

生产者和消费者的问题:

 生产者/消费者问题
  生产者(Productor)将产品交给店员(Clerk),而消费者(Customer)从店员处取走产品,
  店员一次只能持有固定数量的产品(比如:20),如果生产者试图生产更多的产品,店员会叫生产者停一下,
  如果店中有空位放产品了再通知生产者继续生产;如果店中没有产品了,店员会告诉消费者等一下,
  如果店中有产品了再通知消费者来取走产品。

    分析:
    1.是否涉及到多线程的问题?是!生产者、消费者
    2.是否涉及到共享数据?有!考虑线程的安全
    3.此共享数据是谁?即为产品的数量
    4.是否涉及到线程的通信呢?存在这生产者与消费者的通信

class Clerk{//店员
	int product;
	public synchronized void addProduct(){
		if(product>=20){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			product++;
			System.out.println(Thread.currentThread().getName()+": 生产了第"+product+"个产品");
			notifyAll();
		}
	}
	public synchronized void consumeProduct(){
		if(product<=0){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			System.out.println(Thread.currentThread().getName()+": 消费了第"+product+"个产品");
			product--;
			notifyAll();
		}
	}
	
}
class Producer implements Runnable{
	Clerk clerk;
	public Producer(Clerk clerk){
		this.clerk = clerk;
	}
	public void run() {
		System.out.println("生产者开始生产产品...");
		while(true){
			try {
				Thread.currentThread().sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			clerk.addProduct();
		}
		
	}
	
}
class Customer implements Runnable{
    Clerk clerk;
    public Customer(Clerk clerk ){
    	this.clerk = clerk;
    }
	public void run() {
		System.out.println("消费者开始消费产品");
		while(true){
			try {
				Thread.currentThread().sleep(60);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			clerk.consumeProduct();
		}
		
	}
	
}
public class TestProduceCustome {
	public static void main(String[] args) {
		Clerk clerk = new Clerk();
		Producer  p = new Producer(clerk);
		Customer c = new Customer(clerk);
		Thread t1 = new Thread(p);
		Thread t3 = new Thread(p);
		Thread t2 = new Thread(c);
		t1.start();
		t3.start();
		t2.start();
		
	}

}

7.线程的生命周期:

<think>我们根据用户的问题和提供的参考资料,详细讲解C++中std::thread的使用,包括线程创建、管理、同步机制等。 参考资料主要涉及[^1][^2][^3][^4],我们将结合这些内容进行讲解。 内容大纲: 1. 线程创建:使用函数指针、Lambda、函数对象、成员函数等 2. 线程管理:join和detach 3. 线程同步:互斥锁(std::mutex)和条件变量(std::condition_variable)等 4. 参数传递的注意事项 5. 线程局部存储(thread_local) 6. 异常处理 我们将按照上述结构详细展开,并给出代码示例。</think>### C++ `std::thread` 使用详解:线程创建与管理 C++11 引入的 `<thread>` 头文件提供了强大的多线程支持,其中 `std::thread` 是线程管理的核心类。以下是详细使用指南: --- #### 一、线程创建方式 线程可通过多种可调用对象创建: 1. **函数指针** ```cpp void task(int param) { std::cout << "线程执行: " << param << std::endl; } int main() { std::thread t(task, 42); // 创建线程并传递参数 t.join(); } ``` 2. **Lambda 表达式**(推荐) ```cpp std::thread t([](const std::string& msg) { std::cout << "Lambda线程: " << msg << std::endl; }, "Hello Thread"); ``` 3. **函数对象(Functor)** ```cpp struct Task { void operator()(int x) const { std::cout << "函数对象: " << x*x << std::endl; } }; std::thread t(Task{}, 5); // 传递函数对象实例 ``` 4. **类成员函数** ```cpp class Worker { public: void run(const std::string& data) { std::cout << "成员函数线程: " << data << std::endl; } }; Worker w; std::thread t(&Worker::run, &w, "Data"); // 需传递对象指针[^3] ``` --- #### 二、线程生命周期管理 1. **`join()`**:阻塞当前线程直到目标线程完成 ```cpp std::thread t([]{ /* 任务 */ }); t.join(); // 主线程在此等待 ``` 2. **`detach()`**:分离线程(后台运行,无法再控制) ```cpp std::thread t([]{ /* 长时间任务 */ }); t.detach(); // 主线程继续执行 ``` > ⚠️ 警告:未`join()`或`detach()`的线程析构时会调用`std::terminate()`[^2] 3. **`joinable()`**:检查线程是否可管理 ```cpp if (t.joinable()) { t.join(); // 安全操作 } ``` --- #### 三、线程同步机制 避免数据竞争需使用同步原语: 1. **互斥锁 (`std::mutex`)** ```cpp std::mutex mtx; int counter = 0; void safe_increment() { std::lock_guard<std::mutex> lock(mtx); // RAII自动解锁 ++counter; } ``` 2. **条件变量 (`std::condition_variable`)** 实现线程间通信: ```cpp std::condition_variable cv; std::mutex mtx; bool data_ready = false; // 生产者线程 void producer() { std::lock_guard<std::mutex> lock(mtx); data_ready = true; cv.notify_one(); // 通知消费者 } // 消费者线程 void consumer() { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, []{ return data_ready; }); // 阻塞直到条件满足 } ``` --- #### 四、参数传递注意事项 1. **默认按值传递**:参数被复制到线程独立内存空间 ```cpp int x = 10; std::thread t([](int a){ a *= 2; }, x); // x值不变 ``` 2. **引用传递需用 `std::ref` 包装** ```cpp int y = 20; std::thread t([](int& b){ b *= 2; }, std::ref(y)); // y变为40 ``` 3. **移动语义优化大对象** ```cpp std::vector<int> big_data(1000); std::thread t([](std::vector<int>&& data){ // 使用移动后的数据 }, std::move(big_data)); // 转移所有权 ``` --- #### 五、线程局部存储 (`thread_local`) 创建线程私有变量: ```cpp thread_local int thread_id = 0; // 每个线程独立副本 void print_id() { std::cout << "线程ID: " << thread_id++ << std::endl; } int main() { std::thread t1(print_id); // 输出0 std::thread t2(print_id); // 输出0(非1) t1.join(); t2.join(); } ``` --- #### 六、异常处理 线程内异常需捕获处理,否则导致程序终止: ```cpp void risky_task() { try { throw std::runtime_error("线程内部错误"); } catch (const std::exception& e) { std::cerr << "捕获异常: " << e.what() << std::endl; } } ``` --- ### 最佳实践 1. 优先使用 RAII 包装器(如 `std::lock_guard`) 2. 避免全局变量,使用参数传递数据 3. 用 `std::async` 替代 `std::thread` 实现任务并行(简化资源管理)[^4] 4. C++20 推荐 `std::jthread`(自动管理生命周期) ```cpp // std::async 示例 auto future = std::async(std::launch::async, []{ return std::sqrt(2.0); // 异步计算 }); double result = future.get(); // 获取结果 ``` --- ### 相关问题 1. 如何实现线程池以提高大量小任务的性能? 2. `std::atomic` 在无锁编程中如何应用? 3. 多线程调试有哪些常用工具和技巧? 4. C++20 协程如何简化异步编程模型? > 源码示例在 GCC/Clang 需编译选项:`-std=c++11 -pthread` > MSVC 需启用:`/std:c++latest /EHsc` [^1]: 线程创建方式与参数传递机制 [^2]: 线程生命周期管理关键点 [^3]: 类成员函数线程化实现 [^4]: 高级异步任务处理方案
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值