子線程運行執行10次後,主線程再運行5次,這樣交替運行三遍

public class ThreadTest {
    public static void main(String[] args) {
        Bussiness bussiness = new Bussiness();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0;i<3;i++){
                    bussiness.shuMethod();
                }
            }
        }).start();
        for (int i = 0;i < 3;i++){
            bussiness.mainMethod();
        }
    }
     static class Bussiness{
        private boolean subFlag = true;
        public synchronized void mainMethod(){
            while (subFlag){
                try {
                    wait();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            for (int i = 0;i<5;i++){
                System.out.println(Thread.currentThread().getName()+":main thread runing loop count --"+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            subFlag = true;
            notify();
        }
        public synchronized void shuMethod(){
            while (!subFlag){
                try {
                    wait();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            for (int i = 0;i<10;i++){
                System.out.println(Thread.currentThread().getName()+":main thread runing loop count --"+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            subFlag = false;
            notify();
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章