|--需求说明
|--实现方式
嗯 这个可以视作一个经典的消费者和生产者的问题,详细见代码注释
|--代码内容
1 /** 2 * @auther::9527 3 * @Description: 消费者 4 * @program: 多线程 5 * @create: 2019-08-10 10:45 6 */ 7 public class Consumer extends Thread{ 8 private MiddleMan mid = null; 9 10 11 public Consumer() { 12 } 13 14 public Consumer(MiddleMan movie) { 15 this.mid = movie; 16 } 17 18 @Override 19 public void run() { 20 //循环显示50次电影信息 21 for (int i = 0; i <1000 ; i++) { 22 try { 23 Thread.sleep(100); 24 } catch (InterruptedException e) { 25 e.printStackTrace(); 26 } 27 this.mid.get(); 28 } 29 } 30 }
消费者,负责取走生产者产生的信息
1 /** 2 * @auther::9527 3 * @Description: 4 * @program: 多线程 5 * @create: 2019-08-10 10:39 6 */ 7 public class Producer implements Runnable{ 8 //生产数据 9 private MiddleMan mid = null; 10 private boolean flag = false; 11 12 public Producer(MiddleMan movie) { 13 this.mid = movie; 14 } 15 16 public Producer() { 17 } 18 19 @Override 20 public void run() { 21 //循环录入,两部电影交替录人 22 for (int i = 0; i <1000; i++) { 23 if (flag){ 24 this.mid.set("jack说:","我是查水表"); 25 flag = false; 26 } else { 27 this.mid.set("rose说:","你是谁啊?"); 28 flag = true; 29 } 30 } 31 } 32 }
生产者,负责生产信息
1 package com.duo; 2 3 /** 4 * @auther::9527 5 * @Description: 生产者和消费者 6 * @program: 多线程 7 * @create: 2019-08-10 10:36 8 */ 9 public class MiddleMan { 10 private String name; 11 private String info; 12 private boolean flag = true; //设置标志位,控制生产者生产,消费者消费 13 14 public String getName() { 15 return name; 16 } 17 18 public String getInfo() { 19 return info; 20 } 21 22 public MiddleMan(String name, String info) { 23 this.name = name; 24 this.info = info; 25 } 26 27 public MiddleMan() { 28 } 29 30 public synchronized void set(String name,String info){ 31 if (!flag){ 32 try { 33 super.wait(); //当前线程等待 34 } catch (InterruptedException e) { 35 e.printStackTrace(); 36 } 37 } 38 this.name = name; 39 try { 40 Thread.sleep(100); 41 } catch (InterruptedException e) { 42 e.printStackTrace(); 43 } 44 this.info = info; 45 flag = false; //重置标志位,让消费者消费 46 super.notify(); //使用Object的notify方法,让消费者线程被唤醒 47 } 48 public synchronized void get(){ 49 if (flag){ 50 try { 51 super.wait(); 52 } catch (InterruptedException e) { 53 e.printStackTrace(); 54 } 55 } 56 System.out.println(this.getName()+"-"+this.getInfo()); 57 flag = true; 58 super.notify(); //唤醒线程 59 } 60 }
信息中转场地 负责控制生产和消费的节奏
1 /** 2 * @auther::9527 3 * @Description: 测试类 4 * @program: 多线程 5 * @create: 2019-08-10 11:47 6 */ 7 public class Test { 8 public static void main(String[] args) { 9 //生产===>>拿走 生产出来就被拿走 10 MiddleMan mid = new MiddleMan(); 11 Thread producer = new Thread(new Producer(mid)); 12 Thread consumer = new Thread(new Consumer(mid)); 13 producer.start(); 14 consumer.start(); 15 } 16 }
程序入口
|--运行结果
原文地址:https://www.cnblogs.com/twuxian/p/11331077.html
时间: 2024-10-22 09:20:31