java - 扩展线程以测试连接是否正确终止?

标签 java multithreading concurrency

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/

相关文章:

java - DateTime.plusMinutes(..) 返回分钟 -1

c# - 锁定属性,好方法?

java - 如何使用 WatchService 停止用于监视文件夹的线程?

java - 如何在 Spring Boot 中重定向单页应用程序?

C# 等效于 Java 的 mkdirs()

java - 错误: cannot find symbol while calling toString method

Java OKHTTP SocketTimeoutException 与并发多线程请求

linux - iptables 线程安全吗?

c++ - 了解 std::hardware_破坏性_interference_size 和 std::hardware_constructive_interference_size

ios - 主队列异步与默认队列异步说明