java多线程通信

来源:互联网 发布:selenium java client 编辑:程序博客网 时间:2024/06/11 22:15
通过wait和notify实现多线程交替执行,话不多说,直接撸代码!主线程和子线程交替执行 public class TranditionalThreadSynchrized {    public static void main(String[] args){        final Business business;                business = new Business();        //子线程执行        new Thread(new Runnable() {            @Override            public void run() {                for(int i=1; i<=10; i++){                    business.sub(i);                }            }        }).start();        //主线程执行        for(int i=1; i<=10; i++){            business.main(i);        }    }    static class Business{        boolean isExecute = true;        //子线程执行逻辑        public synchronized void sub(int i){            if(isExecute){                for (int j=1; j<=5; j++){                    System.out.println("sub execute " + j + " loop of " + i);                }                isExecute = false;                this.notify();            } else                try {                    this.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }        }        //主线程执行逻辑        public synchronized void main(int i){            if(!isExecute){                for (int j=1; j<=5; j++){                    System.out.println("main execute " + j + " loop of " + i);                }                isExecute = true;                this.notify();            } else                try {                    this.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }        }    }}