多线程顺序打印ABC的三种实现---join方法

【多线程顺序打印ABC的三种实现---join方法】 使用join方法,让三个线程之间存在等待关系
代码如下:

[java]view plain copy

  1. package com.zcj.join;
  2. public class JoinTest {
  3. public static void main(String[] args) {
  4. ThreadA threadA = new ThreadA();
  5. ThreadB threadB = new ThreadB(threadA);
  6. ThreadC threadC = new ThreadC(threadB);
  7. threadA.start();
  8. threadB.start();
  9. threadC.start();
  10. }
  11. }
  12. class ThreadA extends Thread{
  13. @Override
  14. public void run() {
  15. // TODO Auto-generated method stub
  16. System.out.println("A");
  17. }
  18. }
  19. class ThreadB extends Thread{
  20. private ThreadA threadA;
  21. public ThreadB(ThreadA threadA){
  22. this.threadA =threadA;
  23. }
  24. @Override
  25. public void run() {
  26. // TODO Auto-generated method stub
  27. try {
  28. threadA.join();
  29. } catch (InterruptedException e) {
  30. // TODO Auto-generated catch block
  31. e.printStackTrace();
  32. }
  33. System.out.println("B");
  34. }
  35. }
  36. class ThreadC extends Thread{
  37. private ThreadB threadB;
  38. public ThreadC(ThreadB threadB){
  39. this.threadB =threadB;
  40. }
  41. @Override
  42. public void run() {
  43. // TODO Auto-generated method stub
  44. try {
  45. threadB.join();
  46. } catch (InterruptedException e) {
  47. // TODO Auto-generated catch block
  48. e.printStackTrace();
  49. }
  50. System.out.println("C");
  51. }
  52. }
运行结果:

[plain]view plain copy
  1. A
  2. B
  3. C

    推荐阅读