Concurrency 使用任务类启动线程
我想测试扩展javafx.concurrent.task的task类。我已重写调用方法:Concurrency 使用任务类启动线程,concurrency,junit,task,javafx-2,Concurrency,Junit,Task,Javafx 2,我想测试扩展javafx.concurrent.task的task类。我已重写调用方法: public class myTask extends Task<Void> { @Override protected Void call() throws Exception { while(!isCancelled()){ doSth(); } return null; } } 但那没用
public class myTask extends Task<Void> {
@Override
protected Void call() throws Exception {
while(!isCancelled()){
doSth();
}
return null;
}
}
但那没用。在启动的线程中没有调用方法的执行。有人能解释一下为什么会这样吗?JUnit测试不会等待任务线程完成它需要做的事情,并且会在JUnit线程完成后立即终止。您可以通过一个简单的示例来了解该行为: 测试等级:
public class Test1 implements Runnable {
@Override
public void run() {
System.out.println("I'm tired");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
System.out.println("I'm done sleeping");
}
}
测试等级:
public class Test1Test {
@Test
public void testRun() {
Test1 task = new Test1();
Thread th = new Thread(task);
th.start();
boolean yourTestedStuff = true;
assertTrue(yourTestedStuff);
}
}
您将看到,当您运行测试时,它只打印“我累了”,而不打印“我睡不着了”(它甚至可能不打印“我累了”,这取决于线程的交错方式)
您可以使用某种形式的与jUnit线程的同步,例如通过倒计时锁存器,将任务包装在可运行状态中,例如:
@Test
public void testRun() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Test1 task = new Test1();
Runnable r = new Runnable() { //wrap your task in a runnable
@Override
public void run() {
task.run(); //the wrapper calls you task
latch.countDown(); //and lets the junit thread when it is done
}
};
Thread th = new Thread(r);
th.start();
assertTrue(latch.await(1000, TimeUnit.SECONDS)); //force junit to wait until you are done
boolean yourTestedStuff = true;
assertTrue(yourTestedStuff);
}
JUnit测试不会等待您的任务线程完成它需要做的事情,并且会在JUnit线程完成后立即终止。您可以通过一个简单的示例来了解该行为: 测试等级:
public class Test1 implements Runnable {
@Override
public void run() {
System.out.println("I'm tired");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
System.out.println("I'm done sleeping");
}
}
测试等级:
public class Test1Test {
@Test
public void testRun() {
Test1 task = new Test1();
Thread th = new Thread(task);
th.start();
boolean yourTestedStuff = true;
assertTrue(yourTestedStuff);
}
}
您将看到,当您运行测试时,它只打印“我累了”,而不打印“我睡不着了”(它甚至可能不打印“我累了”,这取决于线程的交错方式)
您可以使用某种形式的与jUnit线程的同步,例如通过倒计时锁存器,将任务包装在可运行状态中,例如:
@Test
public void testRun() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Test1 task = new Test1();
Runnable r = new Runnable() { //wrap your task in a runnable
@Override
public void run() {
task.run(); //the wrapper calls you task
latch.countDown(); //and lets the junit thread when it is done
}
};
Thread th = new Thread(r);
th.start();
assertTrue(latch.await(1000, TimeUnit.SECONDS)); //force junit to wait until you are done
boolean yourTestedStuff = true;
assertTrue(yourTestedStuff);
}