设计思路:
生产者1秒生产一个数据
消费者3秒消费一个数据
现在有1个生产者2个消费者
按照常规思想来说生产的数据会多出来。
然后使用SynchronousQueue会生产一个消费一个
package com.example.demo;import java.util.Random;import java.util.concurrent.SynchronousQueue;import java.util.concurrent.TimeUnit;public class SynchronousQueueTest {public static void main(String[] args) {SynchronousQueue<Integer> queue = new SynchronousQueue<Integer>();new Customer1(queue).start();new Customer(queue).start();new Product(queue).start();}static class Product extends Thread {SynchronousQueue<Integer> queue;public Product(SynchronousQueue<Integer> queue) {this.queue = queue;}@Overridepublic void run() {while (true) {int rand = new Random().nextInt(1000);System.out.println("生产了一个产品:" + rand);System.out.println("等待三秒后运送出去...");try {queue.put(rand);} catch (InterruptedException e) {e.printStackTrace();}try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}}}}static class Customer extends Thread {SynchronousQueue<Integer> queue;public Customer(SynchronousQueue<Integer> queue) {this.queue = queue;}@Overridepublic void run() {while (true) {try {try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("0消费了一个产品:" + queue.take());} catch (InterruptedException e) {e.printStackTrace();}System.out.println("------------------------------------------");}}}static class Customer1 extends Thread {SynchronousQueue<Integer> queue;public Customer1(SynchronousQueue<Integer> queue) {this.queue = queue;}@Overridepublic void run() {while (true) {try {try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("1消费了一个产品:" + queue.take());} catch (InterruptedException e) {e.printStackTrace();}System.out.println("------------------------------------------");}}}}
运行
生产了一个产品:385等待三秒后运送出去...1消费了一个产品:385------------------------------------------生产了一个产品:1等待三秒后运送出去...0消费了一个产品:1------------------------------------------生产了一个产品:842等待三秒后运送出去...1消费了一个产品:842------------------------------------------生产了一个产品:190等待三秒后运送出去...0消费了一个产品:190------------------------------------------生产了一个产品:398等待三秒后运送出去...1消费了一个产品:398------------------------------------------生产了一个产品:371等待三秒后运送出去...0消费了一个产品:371------------------------------------------生产了一个产品:783等待三秒后运送出去...
总结达到的效果:
1.只有数据被消费了生产者才会生产,保证了生产和消费的同步
2.只有一个消费者消费数据,保证了数据不可以重复消费
这个是不是很像消息列队的实现!
