二线程交替打印0-100

package com.member.schedule;

public class T {

    public static void main(String[] args) {
        new T().test();
    }

    public void test() {
        Object obj = new Object();
        new Thread(new Runner(obj)).start();
        new Thread(new Runner(obj)).start();
    }

    public class Runner implements Runnable {

        Object obj;

        public Runner(Object obj) {
            this.obj = obj;
        }

        @Override
        public void run() {

            for (int i = 0; i < 100; i++) {
                synchronized (obj) {
                    print(i);
                    try {
                        obj.notifyAll();
                        if (i == 99) {
                            break;
                        }
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
            print("end");
        }

        public void print(Object o) {
            String name = Thread.currentThread().getName();
            System.err.println(name + ":" + o);
        }

    }
}

 

posted on 2017-08-14 16:34  jis117  阅读(233)  评论(0编辑  收藏  举报

导航