线程间的通信

当我们一个数据多个线程都进行操作的时候,我们需要线程间的通信。核心方法是:notify() 和 notifyAll()。这都是object类的方法

1. 线程间通信案例

线程间通信案例的核心是:三个线程操作一个数值,一个线程加,两个线程减。=0的时候不减。

  1. public class TestThread {
  2. private int number = 0;
  3. public synchronized void incre() throws InterruptedException {
  4. while (number != 0) {
  5. this.wait();
  6. }
  7. number = number + 2;
  8. System.out.println(Thread.currentThread().getName() + " 操作后,number的值:" + number);
  9. // 线程通信,通知一个线程。这里由计算机cpu决定通知哪个线程
  10. notify();
  11. // notifyAll() 通知其余的所有线程。
  12. }
  13. public synchronized void decre() throws InterruptedException {
  14. while (number == 0) {
  15. this.wait();
  16. }
  17. number--;
  18. System.out.println(Thread.currentThread().getName() + " 操作后,number的值:" + number);
  19. notify();
  20. }
  21. public static void main(String[] args) {
  22. TestThread testThread = new TestThread();
  23. // 线程1,进行数值加
  24. new Thread(()-> {
  25. try {
  26. for (int i = 0; i < 100; i++) {
  27. testThread.incre();
  28. }
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. }
  32. },"add1").start();
  33. // 线程2,进行数值减
  34. new Thread(()-> {
  35. try {
  36. for (int i = 0; i < 100; i++) {
  37. testThread.decre();
  38. }
  39. } catch (InterruptedException e) {
  40. e.printStackTrace();
  41. }
  42. },"dec1").start();
  43. // 线程3,进行数值减
  44. new Thread(()-> {
  45. try {
  46. for (int i = 0; i < 100; i++) {
  47. testThread.decre();
  48. }
  49. } catch (InterruptedException e) {
  50. e.printStackTrace();
  51. }
  52. },"dec2").start();
  53. }
  54. }

2. API介绍

  • wait():使当前线程一直在等待中。直到另外的线程调用了同一个对象上的notify方法,这时线程结束阻塞。
    • 需要注意的是:
      • wait方法会放弃对象关联的监听器所有权。也就是说:wait会释放锁
      • 还有一种情况是其他线程也有可能会中断当前线程的等待。必须其余线程调用了当前线程的停止方法。
  • 唤醒线程的方法有两种:
    • notify:唤醒正在等待的单条线程,也就是说不管当前有多少个线程在等待,它只会唤醒其中的一条线程,而且这个过程是随机的,这个有CPU来决定。
    • notifyAll:唤醒所有在等待该对象监听器的线程。如果应用中只有两条线程可以采用notify,如果多于两条线程则使用notifyAll方法。

3. 关于虚假唤醒问题

  • 我们在处理判断的时候,要使用while进行处理,否则会出现虚假唤醒的问题。
    • 虚假唤醒发生原因:wait释放锁后,下次在进行启动的时候,会直接从停止的地方唤醒,继续执行下面代码。如果使用while,则每次唤醒都会执行while条件,可以避免上次条件成立,这次不成立造成的虚假唤醒。