线程通信
应用场景:生产者和消费者问题
- 假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库.消费者将仓库中产品取走消费.
- 如果仓库中没有产品,则生产者将产品放入仓库﹐否则停止生产并等待,直到仓库中的产品被消费者取走为止.
- 如果仓库中放有产品﹐则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止.
管程法
package gaoji; //:生产者消费者模型--- --- 利用缓冲区解决:管程法 //生产者,消费者,产品,缓冲区 public class TestPC { public static void main(String[] args) { synContainer synContainer = new synContainer(); scz scz = new scz(synContainer); xfz xfz = new xfz(synContainer); scz.start(); xfz.start(); } } //生产者 class scz extends Thread{ synContainer synContainer; public scz (synContainer synContainer){ this.synContainer=synContainer; } @Override public void run() { for (int i = 1; i <= 100; i++) { synContainer.push(new Chicken(i)); System.out.println("产生了"+i+"只鸡"); } } } //消费者 class xfz extends Thread{ synContainer synContainer; public xfz (synContainer synContainer){ this.synContainer=synContainer; } @Override public void run() { for (int i = 1; i <= 100; i++) { synContainer.pop(); System.out.println("消费了第"+i+"只鸡"); } } } //产品 class Chicken { int id;//产品编号 public Chicken(int id) { this.id = id; } } //缓冲区域 class synContainer{ //容器大小 Chicken[] chickens = new Chicken[10]; int count=0; //生产者放入产品 public synchronized void push(Chicken chicken){ //如果满了需要等待消费者消费 if(count==10){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } chickens[count] = chicken; count++; this.notifyAll(); } public synchronized Chicken pop(){ if(count==0){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } count--; Chicken chicken = chickens[count]; this.notifyAll(); return chicken; } }
信号灯法
package gaoji; public class TestPC2 { public static void main(String[] args) { TV tv = new TV(); new Player(tv).start(); new Look(tv).start(); } } //演员 class Player extends Thread{ TV tv; public Player(TV tv) { this.tv=tv; } @Override public void run() { for (int i = 0; i < 20; i++) { if(i%2==0){ tv.by("大本营"); }else { tv.by("douyin"); } } } } //观众 class Look extends Thread{ TV tv; public Look(TV tv){ this.tv=tv; } @Override public void run() { for (int i = 0; i < 20; i++) { tv.gk(); } } } //节目 class TV { String name; boolean flag=true; public synchronized void by(String name){ if(!flag){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("演员表演了"+name); //提醒观众观看 this.notifyAll(); this.name = name; this.flag= !this.flag; } public synchronized void gk(){ if(flag){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("观看了"+name); this.notifyAll(); this.flag= !this.flag; } }