从计时器设置本地字段
我在单元测试中遇到以下问题。带测试的类:
class TestClass {
boolean stopTest = false;
@Test
public void test() {
// do something
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
stopTest = true;
}
}, 1200);
while(!stopTest) {
}
timer.cancel();
// do assert
}
}
此测试仅在 while 运算符上带有断点的调试中正常工作,但是如果我不在调试中或没有断点的情况下运行测试,他将无限工作。我尝试将 stopTest 更改为带有布尔字段的类,还尝试通过此类中的 get 和 set 方法进行工作。我做错了什么?
I have the following problem in my unit test. The class with tests:
class TestClass {
boolean stopTest = false;
@Test
public void test() {
// do something
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
stopTest = true;
}
}, 1200);
while(!stopTest) {
}
timer.cancel();
// do assert
}
}
This test works right only in debug with breakpoint on while operator, but if I run test not in debug or without breakpoint, he works infinitely. I tried to change stopTest to class with boolean field, also a tried to work through get and set methods in this class. What I do wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于并发的原因需要使用
volatile
修饰符,否则stopTest
无法可靠地更新和读取。有关详细信息,请参阅 JLS §8.3.1.4 -易失性字段。You need to use the
volatile
modifier due to concurrency, otherwisestopTest
cannot be reliably updated and read. For more information, see JLS §8.3.1.4 - volatile Fields.您应该将 stopTest 声明为
volatile
。另请参阅:
易失性
与atomicboolean
同步
方法You should declare stopTest to be
volatile
.See also:
volatile
vsatomicboolean
synchronized
methods@JRL 和@mrkhrts 是对的。但我想提出其他建议。
你真的不需要这里的计时器。您只想在单独的线程中运行一些代码,并使主线程等待,直到该异步任务完成。使用简单的线程和 join() 方法来完成此操作:
@JRL and @mrkhrts are right. But I would like to suggest something else.
You really do not need timer here. You just want to run some code in separat thread and make your main thread to wait until this asynchronous task is done. Do it using simple thread and
join()
method: