什么时候需要通信

多个线程并发执行时, 在默认情况下CPU是随机切换线程的,如果我们希望他们有规律的执行, 就可以使用通信, 例如每个线程执行一次打印。

怎么通信

  • 如果希望线程等待, 就调用wait()
  • 如果希望唤醒等待的线程, 就调用notify();
  • 这两个方法必须在同步代码中执行, 并且使用同步锁对象来调用

演示

需求
实现打印一行英文,打印一行中文

  1. public static void main(String[] args) {
  2. final Printer p = new Printer();
  3. new Thread() {
  4. @Override
  5. public void run() {
  6. while(true) {
  7. p.print1();
  8. }
  9. }
  10. }.start();
  11. new Thread() {
  12. @Override
  13. public void run() {
  14. while(true) {
  15. p.print2();
  16. }
  17. }
  18. }.start();
  19. }
  20. static class Printer {
  21. private int flag = 1;
  22. public void print1(){
  23. synchronized(this) {
  24. /**
  25. * 当flag=1时,才执行,否则等待唤醒
  26. */
  27. if(flag != 1){
  28. try {
  29. this.wait();
  30. } catch (InterruptedException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. System.out.print("你");
  35. System.out.print("好");
  36. System.out.print(", ");
  37. System.out.print("世");
  38. System.out.print("界");
  39. System.out.print("!");
  40. System.out.print("\r\n");
  41. flag = 2;
  42. //随机唤醒单个等待的线程:“我执行完了,该你了”
  43. this.notify();
  44. }
  45. }
  46. public void print2() {
  47. synchronized(this) {
  48. /**
  49. * 当flag=2时,才执行,否则等待唤醒
  50. */
  51. if(flag != 2){
  52. try {
  53. this.wait();
  54. } catch (InterruptedException e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. System.out.print("h");
  59. System.out.print("e");
  60. System.out.print("l");
  61. System.out.print("l");
  62. System.out.print("o");
  63. System.out.print(", ");
  64. System.out.print("w");
  65. System.out.print("o");
  66. System.out.print("r");
  67. System.out.print("l");
  68. System.out.print("d");
  69. System.out.print("!");
  70. System.out.print("\r\n");
  71. flag = 1;
  72. this.notify();
  73. }
  74. }
  75. }
  1. 你好, 世界!
  2. hello, world!
  3. 你好, 世界!
  4. hello, world!
  5. 你好, 世界!
  6. hello, world!
  7. 你好, 世界!
  8. hello, world!
  9. 你好, 世界!
  10. hello, world!
  11. 你好, 世界!
  12. hello, world!
  13. 你好, 世界!
  14. hello, world!
  15. 你好, 世界!
  16. hello, world!
  17. 你好, 世界!
  18. hello, world!
  19. ...
  20. ...
  21. ...