线程通信的几种方式

男娘i 2022-05-17 03:47 438阅读 0赞

1.第一种方式是常见的我们叫它等待唤醒方式吧

  1. public class TestThreadCommunicate {
  2. public static void main(String[] args) {
  3. Communicate communicate = new Communicate();
  4. new Thread(new Runnable() {
  5. @Override
  6. public void run(){
  7. for (int i = 1; i <= 50; i++) {
  8. communicate.sub();
  9. }
  10. }
  11. }).start();
  12. for (int i = 1; i <= 10; i++) {
  13. communicate.main();
  14. }
  15. }
  16. }
  17. class Communicate{
  18. private boolean bool = true;
  19. public synchronized void sub() {
  20. while (!bool) {
  21. try {
  22. // 满足条件那么就等待,所以先不满足条件,等执行完后让子线程等待,主线程执行
  23. this.wait();
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. for (int j = 1; j <= 10; j++) {
  29. System.out.println("childThread......");
  30. }
  31. bool = false;
  32. // 这个唤醒的是下一个线程
  33. this.notify();
  34. }
  35. public synchronized void main() {
  36. while (bool) {
  37. try {
  38. // 当执行完成后让主线程等,子线程执行
  39. this.wait();
  40. } catch (InterruptedException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. for (int j = 1; j <= 50; j++) {
  45. System.out.println("mainThread......");
  46. }
  47. bool = true;
  48. this.notify();
  49. }
  50. }

代码执行过程:先让子线程执行,让主线程等待,等子线程执行完,让主线程执行,子线程等待。

2.使用Condition的方式

  1. public class Condition {
  2. public static void main(String[] args) {
  3. Communicate communicate = new Communicate();
  4. new Thread(new Runnable() {
  5. @Override
  6. public void run(){
  7. for (int i = 1; i <= 50; i++) {
  8. communicate.sub();
  9. }
  10. }
  11. }).start();
  12. for (int i = 1; i <= 10; i++) {
  13. communicate.main();
  14. }
  15. }
  16. static class Communicate{
  17. private boolean bool = true;
  18. Lock lock = new ReentrantLock();
  19. java.util.concurrent.locks.Condition condition = lock.newCondition();
  20. public void sub() {
  21. lock.lock();
  22. try {
  23. while (!bool) {
  24. try {
  25. // 满足条件那么就等待,所以先不满足条件,等执行完后让子线程等待,主线程执行
  26. condition.await();
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. for (int j = 1; j <= 10; j++) {
  32. System.out.println("childThread......");
  33. }
  34. bool = false;
  35. condition.signal();
  36. }finally {
  37. lock.unlock();
  38. }
  39. }
  40. public void main() {
  41. lock.lock();
  42. try {
  43. while (bool) {
  44. try {
  45. // 当执行完成后让主线程等,子线程执行
  46. condition.await();
  47. } catch (InterruptedException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. for (int j = 1; j <= 50; j++) {
  52. System.out.println("mainThread......");
  53. }
  54. bool = true;
  55. condition.signal();
  56. }finally {
  57. lock.unlock();
  58. }
  59. // this.notify();
  60. }
  61. }
  62. }

这个是加锁机制,访问之前加锁,就如同第一个方式的wait。

当然还有其它的方式,自己看吧

发表评论

表情:
评论列表 (有 0 条评论,438人围观)

还没有评论,来说两句吧...

相关阅读

    相关 java实现线通信方式

    前言 在多线程的世界里,线程与线程之间的交互无处不在,只不过在平时的开发过程中,大多数情况下,我们都在单线程的模式下进行编码,即使有,也直接借助框架自身的机制实现了,其实