在某些对并发性要求高的场景中,常常希望提交任务后能立即返回,而执行任务交给其他线程,这是一种MQ的思想,可以用一个BlockingQueue简单实现。

    1. private final Notifier notifier = new Notifier();
    2. public Test() {
    3. ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();
    4. threadPool.execute(notifier);
    5. }
    6. //实质是加入队列
    7. public void work(int time) {
    8. offer(time);
    9. }
    10. private void offer(int time) {
    11. notifier.addTask(time);
    12. }
    13. class Notifier implements Runnable {
    14. BlockingQueue<Integer> tasks = new LinkedBlockingDeque<Integer>();
    15. @Override
    16. public void run() {
    17. for (; ; ) {
    18. int time = 0;
    19. try {
    20. //若队列中没有元素,会一直等待
    21. time = tasks.take();
    22. //执行任务
    23. Thread.sleep(time);
    24. } catch (InterruptedException e) {
    25. e.printStackTrace();
    26. } finally {
    27. System.out.println(Thread.currentThread().getName() + "处理任务" + time);
    28. }
    29. }
    30. }
    31. //入阻塞队列
    32. public void addTask(int time) {
    33. tasks.offer(time);
    34. }
    35. }
    36. public static void main(String[] args) {
    37. //提交完任务后可以立即干其他事
    38. Thread thread = new Thread(() -> {
    39. Test testProducer = new Test();
    40. for (int time = 0; time < 100; time++) {
    41. testProducer.work(time);
    42. }
    43. System.out.println("线程" + Thread.currentThread().getName() + "发布消息");
    44. });
    45. thread.start();
    46. }