多线程生产者消费者问题
生产者消费者模型-->利用缓冲区解决: 管程法
package Thread; /** * @author 85726 * 测试,生产者消费者模型-->利用缓冲区解决: 管程法 */ public class TestPC { public static void main(String[] args) { SynContainer container=new SynContainer(); new Productor(container).start(); new Consumer(container).start(); } } //生产者 class Productor extends Thread{ SynContainer container; public Productor(SynContainer container) { this.container=container; } //生产 @Override public void run() { for (int i = 0; i < 100; i++) { container.push(new Chicken(i)); System.out.println("生产了" + i + "只鸡"); } } } //消费者 class Consumer extends Thread{ SynContainer container; public Consumer(SynContainer container) { this.container=container; } //消费 @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("消费了-->"+container.pop().id+"只鸡"); } } } //产品 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 == chickens.length) { //通知消费者消费,生产等待 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; } }
生产者消费者模型-->信号灯法,标志位解决
1 package Thread; 2 3 import javax.net.ssl.SSLContext; 4 5 //测试生产者消费者问题2:信号灯法,标志位解决 6 public class MyLockTest { 7 public static void main(String[] args) { 8 TV tv=new TV(); 9 new Player(tv).start(); 10 new Watcher(tv).start(); 11 12 } 13 14 } 15 //生产者:演员 16 class Player extends Thread{ 17 TV tv=new TV(); 18 19 public Player(TV tv) { 20 this.tv=tv; 21 } 22 23 @Override 24 public void run() { 25 for (int i = 0; i < 20; i++) { 26 if (i % 3 == 0) { 27 tv.play("插播广告"); 28 }else { 29 tv.play("战狼播放中"); 30 } 31 32 } 33 } 34 } 35 //消费者:观众 36 class Watcher extends Thread{ 37 TV tv=new TV(); 38 39 public Watcher(TV tv) { 40 this.tv=tv; 41 } 42 43 @Override 44 public void run() { 45 for (int i = 0; i < 20; i++) { 46 tv.watch(); 47 } 48 } 49 } 50 //产品:节目 51 class TV{ 52 //演员演戏,观众等待 True 53 //观众观看,演员等待 false 54 55 String voice; //表演的节目 56 boolean flag=true; 57 58 //表演 59 public synchronized void play(String voice) { 60 if (!flag) { 61 try { 62 this.wait(); 63 } catch (InterruptedException e) { 64 e.printStackTrace(); 65 } 66 } 67 System.out.println("演员表演了" + voice); 68 //通知观众观看 69 this.notifyAll(); 70 this.voice=voice; 71 this.flag=!this.flag; 72 73 } 74 75 //观看 76 public synchronized void watch() { 77 if (flag) { 78 try { 79 this.wait(); 80 } catch (InterruptedException e) { 81 e.printStackTrace(); 82 } 83 } 84 System.out.println(" "+"观看了"+voice); 85 //通知演员表演 86 this.notifyAll(); 87 this.flag=!this.flag; 88 } 89 90 }