首页 > 代码库 > 56 主子线程循环执行

56 主子线程循环执行

public class Demo {    public static Object o = new Object();    public static boolean flag = true;    public static void main(String[] args) {        Thread sub = new Thread(new Sub());        sub.start();        mainRun();    }    public static void mainRun() {        try {            for (int i = 1; i <= 5; i++) {                mainExec(i);                Thread.sleep(1000);            }        } catch (Exception e) {            e.printStackTrace();        }    }    public static void mainExec(int num) throws Exception {        synchronized (o) {            if (flag) {                o.wait();            }            for (int i = 1; i <= 20; i++) {                System.out.println(String.format("main-第%s次--%s", num + "", i + ""));            }            flag = true;            o.notify();        }    }    static class Sub extends Thread {        public void run() {            try {                for (int i = 1; i <= 5; i++) {                    subExec(i);                    Thread.sleep(1000);                }            } catch (Exception e) {                e.printStackTrace();            }        }        public void subExec(int num) throws Exception {            synchronized (o) {                if (!flag) {                    o.wait();                }                for (int i = 1; i <= 10; i++) {                    System.out.println(String.format("sub-第%s次--%s", num + "", i + ""));                }                flag = false;                o.notify();            }        }    }}

 

56 主子线程循环执行