【未完】Java--线程之间的通信

不带生产者和消费者之间的通信:

 1  
 2 class SynchronizedMethods{
 3     int d;
 4     synchronized void getDate() {
 5         System.out.println("Got data:"+d);
 6     }
 7     synchronized void putdata(int d) {
 8         this.d=d;
 9         System.out.println("Put data:"+d);
10     }
11 }
12 class  Producer extends Thread{
13     SynchronizedMethods t;
14     public Producer (SynchronizedMethods t) {
15         this.t=t;
16     }
17     public void run() {
18         int data=700;
19         while(true ) {
20             System.out.println("Put called by producer");
21             t.putdata(data++);
22         }
23     }
24     
25 }
26 class Consumer extends Thread {
27     SynchronizedMethods t;
28     public Consumer(SynchronizedMethods t) {
29         this.t=t;
30     }
31     public void run() {
32         while(true) {
33             System.out.println("Get called by consumer");
34             t.getDate();
35         }
36     }
37 }
38 public class ProducerConsumer {
39     public static void main(String args[]) {
40         SynchronizedMethods obj1=new SynchronizedMethods();
41         Producer p=new Producer(obj1);
42         Producer c=new Producer(obj1);
43         p.start();
44         c.start();
45     }
46 }
View Code

无限循环

带有生产者和消费真之间的通信:

猜你喜欢

转载自www.cnblogs.com/Catherinezhilin/p/9056812.html