线程通信
线程通信一般指线程等待唤醒机制,它可以用来解决多线程同步带来的死锁问题
首先我们要明确线程通信是怎么解决死锁的,当你使用synchronized来解决线程安全时,就已经存在死锁的隐患了,因为持有锁的线程在其执行完毕前都不会释放锁,同样在线程获得锁之前线程会处于无期限阻塞状态,所以我们必须手动让其释放自己持有的锁,来让阻塞的线程获得运行。
注意:一旦线程主动释放了自己的锁,会一直处于无限期等待状态,只有持有该线程所释放的锁的线程才能将其唤醒或者超过参数 timeout 设置的超时时间
上述所谈到的释放和唤醒即为线程通信,分别对应方法:
等待
- public final void wait()
- public final void wait(long timeout)
通知
- public final void notify()
- public final void notifyAll()
其中 notify() 是唤醒一个线程而 notifyAll() 是唤醒所有线程
wait()和sleep()的区别:
- wait() 会释放锁
- sleep() 不会释放锁
经典案例
关于线程通信一个很经典的案例:生产者与消费者。
假设有一家蛋糕店,后厨的人需要不断地向柜台中添加蛋糕,而购买的人需要排队从柜台中取出蛋糕。其中后厨的人可以看出生产者,购买的人可以看出消费者,而柜台可以看出线程通信间的存储信息的容器,如下图
我们可以想,当容器为空时,消费者进入wait()状态,需要生产者向容器中添加数据,当容器中有数据时,消费者被唤醒取出数据
而当容器满了时,生产者进入wait()状态,需要消费者从容器中取出数据,当容器数据不满时,生产者被唤醒,向容器中添加数据
以下为队列作为容器实现线程通信的源码(FIFO):
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
Thread thread01 = new Thread(new Produce(myQueue));
Thread thread02 = new Thread(new Consumer(myQueue));
thread01.start();
thread02.start();
}
}
class Produce implements Runnable{
MyQueue myQueue;
public Produce(MyQueue myQueue) {
this.myQueue = myQueue;
}
public void run(){
for (char i = 'A';i<='Z';i++){
myQueue.offer(i);
System.out.println("--------------"+i+"元素入队");
}
}
}
class Consumer implements Runnable{
MyQueue myQueue;
public Consumer(MyQueue myQueue) {
this.myQueue = myQueue;
}
public void run(){
for (int i = 0;i<26;i++){
System.out.println("--------------"+myQueue.poll()+"元素出队");
}
}
}
class MyQueue{
private List<Object> list = new ArrayList<>();
private int max = 4;
public MyQueue(){
}
public MyQueue(int max){
this.max = max;
}
public synchronized void offer(Object o){
while (list.size() == max){
try { this.wait(); } catch (Exception e) { }
}
list.add(o);
this.notifyAll();
}
public synchronized Object poll(){
while (list.size()==0){
try { this.wait(); } catch (Exception e) { }
}
Object o =list.remove(0);
this.notifyAll();
return o;
}
}
本文章仅供个人参考学习,欢迎各位大佬交流与改正