QA

疑问: 为什么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();

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值