Java实现生产者消费者问题


import java.util.Queue;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
public class ProviderConsumerTest{
    public static LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
    public static void main(String[] ar){
        Provider p1=new Provider();
        Provider p2=new Provider();
        Consumer c1=new Consumer();
        Consumer c2=new Consumer();
        Thread tp1=new Thread(p1);
        Thread tp2=new Thread(p2);
        Thread tc1=new Thread(c1);
        Thread tc2=new Thread(c2);
        tp1.setName("Provider1");
        tp2.setName("Provider2");
        tc1.setName("Consumer1");
        tc2.setName("Consumer2");
        tp1.start();
        tp2.start();
        tc1.start();
        tc2.start();

    }
}
class Provider implements Runnable{
    Random random=new Random();
    public void run(){
        for(int i=0;i<5;i++){
                try{
                    int data=random.nextInt();
                ProviderConsumerTest.queue.put(data);
                System.out.println(Thread.currentThread().getName()+" provide "+data);
                Thread.sleep(1000);
                }
                catch(InterruptedException e){
                    e.printStackTrace();
                }
        }
    }
}
class Consumer implements Runnable{
    Random random=new Random();
    Integer data;
    public void run(){
        for(int i=0;i<5;i++){
            try{
                data=ProviderConsumerTest.queue.take();
                System.out.println(Thread.currentThread().getName()+" consume "+data);
                Thread.sleep(1000);
            }
            catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

你可能感兴趣的:(JAVA)