wait和notify

2018-03-06  本文已影响0人  justlinzhihe

今天复习了下Object的wait,notify相关的方法,记录下

public class TestO {
    static Cat[] arr = new Cat[]{new Cat(), new Cat(), new Cat(), new Cat()};
    static AtomicInteger counter = new AtomicInteger(0);

    public synchronized void cc() {
        System.out.println(Thread.currentThread().getName() + " enter TestO");
        Cat cat = get();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            this.wait();
            System.out.println(Thread.currentThread().getName()+" notify");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " end");
    }

    Cat get() {
        return arr[counter.getAndIncrement() & (arr.length - 1)];
    }

    public static void main(String[] args) {
        TestO test = new TestO();
        new MyThread(test).start();
        new MyThread(test).start();
        new MyThread(test).start();
        new MyThread(test).start();
        new MyThread(test).start();
        new MyThread(test).start();
        new MyThread(test).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String cmd = scanner.next();
            synchronized (test) {
                if (cmd.equals("1")) {
                    test.notify();
                } else {
                    test.notifyAll();
                }
            }
        }
    }

    static class MyThread extends Thread {
        TestO object;

        public MyThread(TestO o) {
            this.object = o;
        }

        @Override
        public void run() {
            object.cc();
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读