生产者消费者(举例)

线程A:生产者;

线程B:消费者;

具体场景:

  线程A调用set(String str),给list里面设置字符串,线程B调用get()方法,删除掉list里面的字符串,模拟生产者消费者

  

 1 package com.test1;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 /**
 7  * 
 8 synchronizd可以作用于代码块和方法块上,现在编写一个生产者和消费者的简单例子。
 9 
10 功能:
11 
12 两个线程A,B。对同一个List进行操作。A写入数据,B读取数据。
13 A每次写入一个数据,就会通知B去读取。
14 B每次读取完,就将该数据从List中清除。
15 当List为空的时候,B会一直等待。
16  * @author Administrator
17  *
18  */
19 public class ProduceConsume {
20     List list = new ArrayList();
21     
22     public static void main(String[] args) {
23         final ProduceConsume produceConsume = new ProduceConsume();
24         Runnable runnable1 = new Runnable() {
25             
26             @Override
27             public void run() {
28                 produceConsume.set("hello");
29                 produceConsume.set("world");
30             }
31         };
32         Runnable runnable2 = new Runnable() {
33             
34             @Override
35             public void run() {
36                 while(true){
37                     produceConsume.get();
38                 }
39             }
40         };
41         
42         new Thread(runnable1).start();
43         new Thread(runnable2).start();
44         
45     }
46     
47     public void set(String string){
48         synchronized (list) {
49             list.add(string);
50             list.notifyAll();
51         }
52     }
53     public void get(){
54         synchronized (list) {
55             while(list.isEmpty()){
56                 try {
57                     list.wait();
58                 } catch (InterruptedException e) {
59                     e.printStackTrace();
60                 }
61             }
62             System.out.println("length:"+list.size());
63             System.out.println(list.get(0));
64             list.remove(0);
65         }
66     }
67 }

 

posted @ 2018-09-13 18:22  没有名字~  阅读(777)  评论(0编辑  收藏  举报