zoukankan      html  css  js  c++  java
  • Use Wait & Notify to Implement Two Threads Run Alternatively

    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);
        }
    }
    
    
  • 相关阅读:
    scjp考试准备
    scjp考试准备
    scjp考试准备
    scjp考试准备
    maven学习手记
    maven学习手记
    ExtJS MVC 学习手记3
    调整maven配置文件
    ExtJS MVC学习手记 2
    ExtJS MVC学习手记 1
  • 原文地址:https://www.cnblogs.com/jun-ma/p/6291637.html
Copyright © 2011-2022 走看看