producer and consumer 多线程例子

存储结构,生产者到达最大长度等待消费者消费,没有存储数据,消费者等待生产者生产:
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灵活。

你可能感兴趣的:(多线程)