`
qtlkw
  • 浏览: 301601 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

producer and consumer 多线程例子

    博客分类:
  • JAVA
 
阅读更多
存储结构,生产者到达最大长度等待消费者消费,没有存储数据,消费者等待生产者生产:
package ProductConsumer;

import java.util.LinkedList;
import java.util.List;
import java.util.Date;
/**
 * Created by Administrator
*/
public class EventStorage {
    private int maxSize;
    private List<Date> storage;

    public EventStorage(){
        maxSize = 10;
        storage = new LinkedList<Date>();
    }

    public synchronized  void set(){
        while(storage.size() == maxSize){
            try{
                wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }

        storage.add(new Date());
        System.out.printf("Set: %d\n", storage.size());
        notifyAll();
    }

    public synchronized void get(){
        while(storage.size() == 0){
            try{
                wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }

        System.out.printf("Get: %d: %s\n", storage.size(), ((LinkedList<?>)storage).poll());
        notifyAll();
    }
}


生产者:
public class Producer implements Runnable {
    private EventStorage storage;
    public Producer(EventStorage storage){
        this.storage = storage;
    }

    @Override
    public void run(){
        for(int i=0; i<100; i++){
            storage.set();
        }
    }
}


消费者:
public class Consumer implements Runnable {
    private EventStorage storage;

    public Consumer(EventStorage storage){
        this.storage = storage;
    }

    @Override
    public void run(){
        for(int i=0; i<100; i++){
            storage.get();
        }
    }
}

public class Main {
    public static void main(String[] args){
        EventStorage storage = new EventStorage();

        Producer producer = new Producer(storage);
        Thread thread1 = new Thread(producer);

        Consumer consumer = new Consumer(storage);
        Thread thread2 = new Thread(consumer);

        thread2.start();
        thread1.start();
    }
}


notify和wait比synchronized灵活。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics