交替打印0-100

package com.wolaidai.loanprocedure;

public class ABC {

    public static void main(String[] args) throws Exception {

        Object obj = new Object();
        new Thread(new Printer(obj)).start();
        new Thread(new Printer(obj)).start();
    }

    Object obj;

    static class Printer implements Runnable {
        Object obj;

        Printer(Object obj) {
            this.obj = obj;
        }

        @Override
        public void run() {
            String name = Thread.currentThread().getName();
            int i = 0;
            do {
                synchronized (obj) {
                    obj.notifyAll();
                    System.err.println(name + " :" + i);
                    try {
                        if (i >= 100) {
                            break;
                        }
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } while (i++ <= 100);
        }
    }

}

 

posted on 2017-09-11 09:22  jis117  阅读(238)  评论(0编辑  收藏  举报

导航