QA

来源:互联网 发布:淘宝女士t恤 编辑:程序博客网 时间:2024/04/28 14:23

疑问: 为什么t1.open() 调用notifyAll()的时候,t2, t3为什么不释放?还在wait等待状态

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * Created by arthur.dy.lee on 2017/6/29. *///public class Test implements Runnable {public class MyThread extends Thread {    public boolean isOpen;    private Integer generation = 1;    public synchronized void open() {        ++generation;        isOpen = true;        notifyAll();    }    public synchronized void close() {        isOpen = false;    }    public synchronized void wait1() {        while (!isOpen) {            System.out.println(currentThread().getName() + ", in while");            try {                wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        System.out.println(currentThread().getName() + ", out while");    }    public synchronized void wait2() {        int arrivalGeneration = generation;        while (!isOpen && arrivalGeneration == generation) {            System.out.println(currentThread().getName() + ", in while");            try {                wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        System.out.println(currentThread().getName() + ", out while");    }    public void run() {//        wait2();        wait1();        System.out.println(currentThread().getName());    }    public boolean isOpen() {        return isOpen;    }    public void setOpen(boolean open) {        isOpen = open;    }    public static void main(String[] args) throws InterruptedException {        Object obj;        ExecutorService pool = Executors.newFixedThreadPool(5);        // 创建线程        MyThread t1 = new MyThread();        MyThread t2 = new MyThread();        MyThread t3 = new MyThread();        // 将线程放入池中进行执行        pool.execute(t1);        pool.execute(t2);        pool.execute(t3);        long t0 = System.currentTimeMillis();        for (; ; ) {            if ((System.currentTimeMillis() - t0) > 100) {                break;            }        }        t1.open();        /*            t1.join();            synchronized (MyThread.class) {            System.out.println("get lock, "+currentThread().getName());            t3.notifyAll();        }*/        //t2.open();        //t1.close();        //t3.open();        //        t3.open();        //TimeUnit.SECONDS.sleep(2);        //        System.out.println("t2.close");//        t2.close();//        t3.close();        // 关闭线程池        pool.shutdown();    }}