在某些对并发性要求高的场景中,常常希望提交任务后能立即返回,而执行任务交给其他线程,这是一种MQ的思想,可以用一个BlockingQueue简单实现。
private final Notifier notifier = new Notifier();public Test() {ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();threadPool.execute(notifier);}//实质是加入队列public void work(int time) {offer(time);}private void offer(int time) {notifier.addTask(time);}class Notifier implements Runnable {BlockingQueue<Integer> tasks = new LinkedBlockingDeque<Integer>();@Overridepublic void run() {for (; ; ) {int time = 0;try {//若队列中没有元素,会一直等待time = tasks.take();//执行任务Thread.sleep(time);} catch (InterruptedException e) {e.printStackTrace();} finally {System.out.println(Thread.currentThread().getName() + "处理任务" + time);}}}//入阻塞队列public void addTask(int time) {tasks.offer(time);}}public static void main(String[] args) {//提交完任务后可以立即干其他事Thread thread = new Thread(() -> {Test testProducer = new Test();for (int time = 0; time < 100; time++) {testProducer.work(time);}System.out.println("线程" + Thread.currentThread().getName() + "发布消息");});thread.start();}
