线程通信
当多个线程操作共享多资源时,线程间通过某种方式相互告知自己的状态,以相互协调, 并避免无效的资源争夺。
线程通信的常见模型(生产者与消费者模型)
生产者线程负责生产数据
消费者线程负责消费生产者生产的数据。
生产者生产完数据应该等待自己,通知消费者,消费者消费完数据也应该等待自己, 再通知生产者生产。
public class ThreadCommunication {public static void main(String[] args) {Desk desk = new Desk();//生产者线程new Thread(()->{while (true) {desk.put();}},"厨师1").start();new Thread(()->{while (true) {desk.put();}},"厨师2").start();new Thread(()->{while (true) {desk.put();}},"厨师3").start();//消费者线程new Thread(()->{while (true) {desk.get();}},"吃货1").start();//消费者线程new Thread(()->{while (true) {desk.get();}},"吃货2").start();}
}
public class Desk {private ArrayList<String> list = new ArrayList<String>();//厨师1 2 3public synchronized void put() {try {final Thread thread = Thread.currentThread();if (list.size() == 0) {list.add(thread.getName()+"做的包子");System.out.println(thread.getName()+"做了一个包子");Thread.sleep(2000);//做完了事情,等待自己,让出机器资源, 唤醒别人} else {//有包子了, 就不做了//唤醒别人//等待自己}this.notifyAll();//唤醒别人this.wait(); //等待自己} catch (Exception e) {e.printStackTrace();}}//吃货1 ,2public synchronized void get() {try {final Thread thread = Thread.currentThread();if (list.size() == 1) {//有包子了System.out.println(thread.getName() + "吃了"+list.get(0));list.clear();Thread.sleep(1000);this.notifyAll();this.wait();} else {//没有包子this.notifyAll();this.wait();}} catch (InterruptedException e) {e.printStackTrace();}}
}