Java 并发实践,12.1.2。测试阻塞操作:
void testTakeBlocksWhenEmpty() {
final BoundedBuffer<Integer> bb = new BoundedBuffer<Integer>(10);
Thread taker = new Thread() {
public void run() {
try {
int unused = bb.take();
fail(); // if we get here, it’s an error
} catch (InterruptedException success) { }
}
};
try {
taker.start();
Thread.sleep(LOCKUP_DETECT_TIMEOUT);
taker.interrupt();
taker.join(LOCKUP_DETECT_TIMEOUT);
assertFalse(taker.isAlive());
} catch (Exception unexpected) {
fail();
}
}
This is one of the few cases in which it is appropriate to subclass Thread explicitly instead of using a Runnable in a pool: in order to test proper termination with join. The same approach can be used to test that the taker thread unblocks after an element is placed in the queue by the main thread.
但我看不出扩展 Thread 对测试有何帮助。对我来说,似乎可以通过将 Runnable
传递给 Thread
来完成相同的测试。有人可以解释一下吗?
最佳答案
This is one of the few cases in which it is appropriate to subclass Thread explicitly instead of using a Runnable in a pool: in order to test proper termination with join.
换句话说,该方法让您有机会中断测试线程并加入它以确保它已正确终止。例如,如果您使用 ThreadPoolExecutor
类,则无法以这种方式处理线程。
此外,可以创建一个新线程,使用 Runnable 启动它,例如 Thread taker = new Thread(() -> {...});
。请记住,这本书是大约 8 年前写的,创建 Runnable
而不是 Thread
的子类会使该示例更长一些。
关于java - 扩展线程以测试连接是否正确终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53342444/