读书人

重写CountDownLatch以兑现线程状态监视

发布时间: 2012-12-26 14:39:28 作者: rapoo

重写CountDownLatch以实现线程状态监视

需求:管理线程需要及时知道工作线程全部处于等待状态,并满足等待条件让他们恢复运行。

?

思想:有一种方法是“心跳方法”,让工作线程定时向管理线程“报到”。而这里我想通过并发的状态计数来实现状态监视。jdk提供有两种并发的状态计数:java.util.concurrent.CountDownLatch 和 java.util.concurrent.CyclicBarrier 。CountDownLatch 初始化后,工作线程调用countDown方法,计数减为0以前,调用await方法的其他线程会一直阻塞。它适用于一个或几个其他线程等待一组线程都经过某点的情形,但有一个局限,即它是一次性的能重置。CyclicBarrier 可以重置,但它只适用于一组线程分别到达某点后互相等待以实现步调一致的情形。(见JDK 1.6)

??? 于是我考虑修改CountDownLatch 类,使其支持重置,以胜任连续监视的需求。

?

代码如下:

修改后的新计数器类:ResetableCountDownLatch

?

测试用例:

?

?

测试输出:

Thread-1 start.Thread-2 start.Thread-0 start.Thread-2 wait 1time(s)Thread-0 wait 1time(s)Thread-1 wait 1time(s)Main: there are 3 live threads all waitingMain: wake them up.Thread-1 continue.Thread-2 continue.Thread-0 continue.Thread-2 wait 2time(s)Thread-0 wait 2time(s)Thread-1 wait 2time(s)Main: there are 3 live threads all waitingMain: wake them up.Thread-1 continue.Thread-0 continue.Thread-2 continue.Thread-2 wait 3time(s)Thread-1 wait 3time(s)Thread-0 wait 3time(s)Main: there are 3 live threads all waitingMain: wake them up.Thread-0 continue.Thread-1 continue.Thread-2 continue.Thread-2 wait 4time(s)Thread-0 wait 4time(s)Thread-1 wait 4time(s)Main: there are 3 live threads all waitingMain: wake them up.Thread-1 continue.Thread-2 continue.Thread-0 continue.Thread-1 wait 5time(s)Thread-2 wait 5time(s)Thread-0 wait 5time(s)Main: there are 3 live threads all waitingMain: wake them up.Thread-0 continue.Thread-2 continue.Thread-1 continue.Thread-0 wait 6time(s)Thread-1 wait 6time(s)Thread-2 wait 6time(s)Main: there are 3 live threads all waitingMain: wake them up.Thread-2 continue.Thread-1 continue.Thread-0 continue.Thread-2 wait 7time(s)Thread-1 wait 7time(s)Thread-0 wait 7time(s)Main: there are 3 live threads all waitingMain: wake them up.Thread-0 continue.Thread-1 continue.Thread-2 continue.Thread-0 wait 8time(s)Thread-1 wait 8time(s)Thread-2 wait 8time(s)Main: there are 3 live threads all waitingMain: wake them up.Thread-1 continue.Thread-2 continue.Thread-0 continue.Thread-0 finish.Thread-2 wait 9time(s)Thread-1 wait 9time(s)Main: there are 2 live threads all waitingMain: wake them up.Thread-2 continue.Thread-1 continue.Thread-1 finish.Thread-2 wait 10time(s)Main: there are 1 live threads all waitingMain: wake them up.Thread-2 continue.Thread-2 finish.Main: All threads finished.

?

1 楼 flysnail 2012-11-05 思路挺好,:) 2 楼 nudtgk2000 2012-11-05 flysnail 写道 思路挺好,
谢谢鼓励,还是初学者,不懂的太多。:)

读书人网 >编程

热点推荐