温故一下上一节所学习的生产者消费者代码:

两个线程时:

通过标志位flag的if判断和同步函数互斥较好解决两个线程,一个生产者、一个消费者交替执行的功能

类名:ProducterConsumerDemo.java

代码:

 1 class  ProducterConsumerDemo
 2 {
 3     public static void main(String[] args) 
 4     {
 5         Resources  r =new Resources();
 6         Productor  pro =new Productor(r);
 7         Consumer   con = new Consumer(r);
 8         
 9         Thread t1 =new Thread(pro);
10         Thread t2 =new Thread(con);
11         t1.start();
12         t2.start();
13         System.out.println("Hello World!");
14     }
15 }
16 
17 class Resources
18 {
19     private String name;
20     private int count =1;
21     private boolean flag =false;
22 
23     public synchronized void set(String name)
24     {
25        if(flag)
26            try{this.wait();}catch(Exception e){}
27        this.name = name+"--"+count++;
28 
29        System.out.println(Thread.currentThread().getName()+"生产者"+this.name);
30        flag =true;
31        //唤醒对方进程
32        this.notify();
33 
34     }
35     public synchronized void out()
36     {
37        if(!flag)
38            try{this.wait();}catch(Exception e){}
39        
40        System.out.println(Thread.currentThread().getName()+" ....消费者...."+this.name);
41        flag =false;
42        //唤醒对方进程
43        this.notify();
44 
45     }
46 }
47 
48 class Productor implements Runnable
49 {
50     private Resources res;
51     Productor(Resources res){
52         this.res =res;
53     }
54     public void run(){
55         while(true){
56             res.set("++商品++");
57         }
58     }
59 
60 }
61 
62 class Consumer  implements Runnable
63 {
64     private Resources res;
65     Consumer(Resources res){
66         this.res =res;
67     }
68     public void run(){
69         while(true){
70             res.out();
71         }
72     }
73 
74 }
ProducterConsumerDemo.java

相关文章: