[Linux#43][线程] 死锁 | 同步 | 基于 BlockingQueue 的生产者消费者模型
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
 
public class ProducerConsumerWithBlockingQueue {
 
    private final BlockingQueue<String> queue;
 
    public ProducerConsumerWithBlockingQueue() {
        this.queue = new LinkedBlockingQueue<>();
    }
 
    public void start() throws InterruptedException {
        Thread producerThread = new Thread(new Producer());
        Thread consumerThread = new Thread(new Consumer());
 
        producerThread.start();
        consumerThread.start();
 
        producerThread.join();
        consumerThread.join();
    }
 
    private class Producer implements Runnable {
        @Override
        public void run() {
            try {
                queue.put("Item");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
 
    private class Consumer implements Runnable {
        @Override
        public void run() {
            try {
                String item = queue.take();
                System.out.println("Consumed: " + item);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
 
    public static void main(String[] args) {
        ProducerConsumerWithBlockingQueue example = new ProducerConsumerWithBlockingQueue();
        try {
            example.start();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}这段代码展示了如何使用BlockingQueue来避免死锁。Producer向队列中放入一个项目,而Consumer从队列中取出一个项目并打印。如果队列为空,take方法会阻塞等待直到有项目可用。如果队列满,put方法会阻塞等待直到队列中有空间。这样,生产者和消费者之间通过队列进行同步,避免了直接同步导致的死锁问题。
评论已关闭