• java 实现线程间通信


    1、使用线程池管理线程。

    2、使用synchronized实现线程间同步。

    3、使用wait()方法让当前线程等待;使用notify()方法唤起wait中的线程。

    4、使用CountDownLatch等待线程结束。

    上代码

    1. package com.thread;
    2. import java.util.concurrent.CountDownLatch;
    3. import java.util.concurrent.ExecutorService;
    4. import java.util.concurrent.Executors;
    5. import java.util.concurrent.TimeUnit;
    6. public class TasksCommunicate extends Thread {
    7. private static final int size = 12;
    8. private static StringBuilder sb = new StringBuilder();
    9. private static Integer num = 0;
    10. private String name;
    11. private CountDownLatch countDownLatch;
    12. public TasksCommunicate(String name, CountDownLatch countDownLatch) {
    13. this.name = name;
    14. this.countDownLatch = countDownLatch;
    15. }
    16. @Override
    17. public void run() {
    18. while (num < size) {
    19. synchronized (TasksCommunicate.class) {
    20. num = num + 1;
    21. System.out.println("thread_" + name + " 打印:" + sb.toString());
    22. sb = new StringBuilder("thread_" + name + "已完成自增1,目前num=" + num + ",请知晓!");
    23. TasksCommunicate.class.notify();
    24. try {
    25. if (num < size) {
    26. TasksCommunicate.class.wait();
    27. }
    28. } catch (InterruptedException e) {
    29. e.printStackTrace();
    30. }
    31. }
    32. }
    33. countDownLatch.countDown();
    34. System.out.println("thread_" + name + " 结束!");
    35. }
    36. public static void main(String[] args) {
    37. CountDownLatch countDownLatch = new CountDownLatch(2);
    38. Thread thread0 = new TasksCommunicate("A", countDownLatch);
    39. Thread thread1 = new TasksCommunicate("B", countDownLatch);
    40. ExecutorService executor = Executors.newFixedThreadPool(2);
    41. executor.submit(thread0);
    42. executor.submit(thread1);
    43. try {
    44. countDownLatch.await(3, TimeUnit.SECONDS);
    45. } catch (InterruptedException e) {
    46. e.printStackTrace();
    47. }
    48. executor.shutdown();
    49. System.out.println("进程结束,退出!!!");
    50. }
    51. }

    打印输出:

    thread_A 打印:
    thread_B 打印:thread_A已完成自增1,目前num=1,请知晓!
    thread_A 打印:thread_B已完成自增1,目前num=2,请知晓!
    thread_B 打印:thread_A已完成自增1,目前num=3,请知晓!
    thread_A 打印:thread_B已完成自增1,目前num=4,请知晓!
    thread_B 打印:thread_A已完成自增1,目前num=5,请知晓!
    thread_A 打印:thread_B已完成自增1,目前num=6,请知晓!
    thread_B 打印:thread_A已完成自增1,目前num=7,请知晓!
    thread_A 打印:thread_B已完成自增1,目前num=8,请知晓!
    thread_B 打印:thread_A已完成自增1,目前num=9,请知晓!
    thread_A 打印:thread_B已完成自增1,目前num=10,请知晓!
    thread_B 打印:thread_A已完成自增1,目前num=11,请知晓!
    thread_A 结束!
    thread_B 结束!
    进程结束,退出!!!

  • 相关阅读:
    简单易懂的进程与线程详解
    音视频过滤器实战--音频混音
    【博客438】Kubernetes IPAM分配IP原理
    (四)笔记.net core学习之应用配置、多环境配置、日志与路由
    2023年数维杯国际赛B题实现代码
    Ubuntu下通过python使用MySQL
    Docker是什么?使用场景作用及Docker的安装和启动详解
    npm: node package manager,node包管理器
    05-前端基础CSS第三天
    Pycharm中配置服务器中的Jupyter并使用
  • 原文地址:https://blog.csdn.net/jiahao1186/article/details/126834195