import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class ProducerConsumer { public static void main(String[] args) { BlockingQueuequeue = new LinkedBlockingQueue<>(5); Thread producer = new Thread(() -> { try { queue.put("message"); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread consumer = new Thread(() -> { try { String message = queue.take(); System.out.println(message); } catch (InterruptedException e) { e.printStackTrace(); } }); producer.start(); consumer.start(); } }
import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class ThreadPool { private BlockingQueueBoth examples use the java.util.concurrent.BlockingQueue interface to manage the communication between threads. The BlockingQueue is part of the java.util.concurrent package.queue; public ThreadPool(int poolSize, int queueSize) { queue = new LinkedBlockingQueue (queueSize); for (int i = 0; i < poolSize; i++) { Thread t = new Thread(() -> { while (true) { try { Runnable task = queue.take(); task.run(); } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); } } public void submit(Runnable task) { try { queue.put(task); } catch (InterruptedException e) { e.printStackTrace(); } } }