例子:生产者-厨师 消费者-客人
public class Table { LinkedList<Object> list = new LinkedList<>(); private static final int Max=100; //存储产品 public synchronized void store(String product){ //如果仓库已满 生产者等待; while (list.size()>Max){ try { this.wait(); //wait();notify()这两个在同步代码块中,由锁对象调用 } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+"++存储了"+product);//把产品存进去 list.offer(product); } //取产品 public synchronized void take(){ //判断仓库是否为空,当仓库空时需要等待 while (list.size() <= 0){ try{ this.wait(); }catch (InterruptedException e){ e.printStackTrace(); } } Object product = list.poll();//把前面的产品取出来 System.out.println(Thread.currentThread().getName()+"--消费了"+product); //通知生产者继续生产 this.notify(); } }
public class Product extends Thread { private Table table; public Product(Table table) { super(); this.table = table; } @Override public void run(){ for(int i=0;i<30;i++){ String product = "产品编号:"+new Random().nextInt(100); table.store(product); } } }
public class ConsumerThread extends Thread { private Table table; public ConsumerThread(Table table) { super(); this.table = table; } @Override public void run(){ for(int i=0;i<30;i++){ table.take(); } } }
class test{ public static void main(String[] args) { //创建桌子 Table table = new Table(); //创建3个生产者线程模拟三个人 Product p1= new Product(table); Product p2= new Product(table); Product p3= new Product(table); p1.setName("张三"); p2.setName("李四"); p3.setName("王五"); p1.start(); p2.start(); p3.start(); ConsumerThread c1 = new ConsumerThread(table); ConsumerThread c2 = new ConsumerThread(table); ConsumerThread c3 = new ConsumerThread(table); c1.setName("吃货1号"); c2.setName("吃货2号"); c3.setName("吃货3号"); c1.start(); c2.start(); c3.start(); } }
public class PrintNum { private int num=0; //打印奇数 public synchronized void printJi(){ //当num是偶数时需要等待 while (num % 2==0){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+":"+num); num++; //通知打印偶数 this.notify(); } //打印偶数 public synchronized void printOu(){ //当num是奇数时需要等待 while (num % 2==1){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+":"+num); num++; //通知打印奇数 this.notify(); } } class test09{ public static void main(String[] args) { PrintNum printNum = new PrintNum(); new Thread(new Runnable() { @Override public void run() { while (true){ printNum.printJi(); } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true){ printNum.printOu(); } } }).start(); } }