利用ArrayBlockingQueue实现生产者-消费者

生产者:

import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {
    private BlockingQueue queue;  
    public Producer(BlockingQueue q){
        this.queue=q;
    }
    @Override
    public void run() {
        //produce Strings
        for(int i=0; i<100; i++){
            String msg = i+"";
            try {
                Thread.sleep(i);
                queue.put(msg);
                System.out.println("Produced "+msg);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //adding exit String
        String msg = new String("exit");
        try {
            queue.put(msg);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

消费者:

import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable{

private BlockingQueue queue;
    
    public Consumer(BlockingQueue q){
        this.queue=q;
    }

    @Override
    public void run() {
        try{
            String msg;
            //consuming Strings until exit String is received
            while(!(msg = queue.take()).equals("exit")){
            Thread.sleep(10);
            System.out.println("Consumed "+msg);
            }
        }catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}

测试:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProducerConsumerService {

    public static void main(String[] args) {
        //Creating BlockingQueue of size 10
        BlockingQueue queue = new ArrayBlockingQueue<>(10);
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);
        //starting producer to produce Strings in queue
        new Thread(producer).start();
        //starting consumer to consume Strings from queue
        new Thread(consumer).start();
        System.out.println("Producer and Consumer has been started");
    }

}


你可能感兴趣的:(java)