码迷,mamicode.com
首页 > 编程语言 > 详细

56 主子线程循环执行

时间:2014-08-26 01:45:05      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   for   ar   2014   art   

bubuko.com,布布扣

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 主子线程循环执行

标签:style   blog   http   color   io   for   ar   2014   art   

原文地址:http://www.cnblogs.com/seven7seven/p/3936234.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!