public class ThreadCommunication {
    public static void main(String[] args) {
        Business business = new Business();
        new Thread(() -> {
            while (true) {
                try {
                    business.thread1();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(() -> {
            while (true) {
                try {
                    business.thread2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

class Business {
    private boolean thread1First = true;

    public synchronized void thread1() throws InterruptedException {
        while (!thread1First) {
            this.wait();
        }
        thread1First = !thread1First;
        this.notify();
        System.out.println("thread 1 is called!!!");
        Thread.sleep(1000);
    }

    public synchronized void thread2() throws InterruptedException {
        while (thread1First) {
            this.wait();
        }

        thread1First = !thread1First;
        this.notify();
        System.out.println("thread 2 is invoked");
        Thread.sleep(1000);
    }
}

相关文章:

  • 2022-02-13
  • 2021-06-18
  • 2021-12-30
  • 2021-06-23
  • 2022-02-22
  • 2021-06-02
  • 2022-12-23
猜你喜欢
  • 2021-04-30
  • 2021-08-01
  • 2021-05-24
  • 2022-12-23
  • 2021-12-26
  • 2022-01-24
相关资源
相似解决方案