1 import javax.swing.plaf.SliderUI;
2
3 /*
4 * 生产者Producter
5 * 仓库Godown
6 * 消费者 Consumer
7 * 生产者和消费者通过仓库而建立起联系,仓库的当前数量低于最大库存量时,生产者线程不断生产产品(修改Godown类的属性的值)
8 * 仓库的产品数量大于0时,消费者不断取出产品(修改Godown类的属性的值).当生产者生产的产品等于最大库存值时,
9 * 停止生产,当产品数量小于0时,消费者停止消费
10 *
11 * 分析:
12 * 1涉及到多线程:生产者和消费者,并且可能有多个生产者和多个消费者
13 * 2涉及数据共享:仓库的产品数量会被多个生产者和消费者共同操作
14 * 生产者与生产者的同步 生产者与消费者的同步 消费者与消费者的同步(synchronized)
15 * 3涉及到线程的通讯:生产者与消费者的通讯(wait和notify)
16 */
17
18 public class ThreadDemo {
19
20 /**
21 * @param args
22 */
23 public static void main(String[] args) {
24 Godown godown = new Godown(); //创建一个产品仓库
25 Consumer cs = new Consumer(godown); //创建消费者目标对象并使消费者共享该仓库
26 Producter pd = new Producter(godown);//创建生产者目标对象并使其共享该仓库
27 Thread tr1 = new Thread(pd); //创建一个生产者线程
28 Thread tr2 = new Thread(pd); //创建第二个生产者线程
29 Thread tr3 = new Thread(cs); //创建一个消费者线程
30 tr1.setName("一号生产者线程"); //修改线程名称
31 tr2.setName("二号生产者线程");
32 tr3.setName("一号消费者者线程");
33 tr1.start(); //启动线程
34 tr2.start();
35 tr3.start();
36
37 }
38
39
40 }
41 /*
42 * 消费者
43 */
44 class Consumer implements Runnable{
45 private Godown godown;
46 private Boolean boolea = true;
47 public Consumer(Godown godown){
48 this.godown = godown;
49 }
50 @Override
51 public void run() { //不断的取出产品
52 while(boolea){
53 godown.Consumption();
54 }
55
56 }
57 }
58 /*
59 * 生产者
60 */
61 class Producter implements Runnable{
62
63 private Godown godown;
64 private Boolean boolea = true;
65 public Producter(Godown godown){
66 this.godown = godown;
67 }
68 @Override
69 public void run() {
70 while(boolea){ //不断的生产产品
71 godown.Production();
72 }
73
74 }
75
76 }
77
78 class Godown{
79 public static final int max_size = 100; //最大库存量
80 public int curnum; //当前库存量默认为0
81 public synchronized void Production(){ //生产产品
82 if(curnum<max_size){ //如果满足生产条件则开始生产
83 curnum++;
84 notify();//生产了产品后通知休眠进程可以工作了(如果唤醒的是别的生产线程,因为共同的对象锁此时处于锁定状态,
85 //所以被唤醒的生产线程会阻塞,如果唤醒的是消费者线程,则消费者线程开始工作)
86 System.out.println(Thread.currentThread().getName()+"生产一个产品 当前剩余产品数量: "+curnum);
87 try {
88 Thread.currentThread().sleep(250); //控制生产的速度
89
90 } catch (InterruptedException e) {
91 e.printStackTrace();
92 }
93 }else{
94
95 try {
96 wait(); //不满足生产条件时,生产者线程释放当前的对象锁,进入休眠状态
97 } catch (InterruptedException e) {
98 e.printStackTrace();
99 }
100 }
101 }
102 public synchronized void Consumption(){
103 if(curnum>0){
104
105 notify();
106 curnum--;
107 System.out.println(Thread.currentThread().getName()+"消费一个产品 当前剩余产品数量: "+curnum);
108 try {
109 Thread.currentThread().sleep(300);
110
111 } catch (InterruptedException e) {
112
113 e.printStackTrace();
114 }
115 }else{
116 try {
117 wait();
118 } catch (InterruptedException e) {
119
120 e.printStackTrace();
121 }
122
123 }
124 }
125 }