简体   繁体   English

java.util.concurrent:从Runnable到Executor接口的过渡

[英]java.util.concurrent: Transition from Runnable to Executor interface

I am writing a JUnit test case for a DSL, and I need to ensure that the method under test does never end (as in this question ). 我正在为DSL编写JUnit测试用例,并且需要确保被测方法永远不会结束(如本问题所述 )。

The provided solution is fine, but I would like to use the "new" Executor interface (Java 5.0 onwards): 提供的解决方案很好,但是我想使用“新的” Executor接口 (从Java 5.0开始):

@Test
public void methodDoesNotReturnFor5Seconds() throws Exception {
  Thread t = new Thread(new Runnable() {
    public void run() {
      methodUnderTest();
    }
  });
  t.start();
  t.join(5000);
  assertTrue(t.isAlive());
  // possibly do something to shut down methodUnderTest
}

How can I translate the above code from the "old" Thread / Runnable interface to the "new" ExecutorService / Executor interface? 如何从“旧”上面的代码翻译Thread / Runnable接口的“新” ExecutorService / Executor接口?

Future<?> future = Executors.newSingleThreadExecutor().submit(new Runnable() {
    public void run() {
        methodUnderTest();
    } 
});
try {
    future.get(5, TimeUnit.SECONDS);
    fail("The task has completed before 5 seconds");
}
catch (TimeoutException e) {
    // expected
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM