我对 Java 还很陌生,想知道这段代码哪里出了问题
for(int i=0; i<10; i++) {
textArea.setText("\n***Iterate***\n");
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
}
}
我期望这样做的是对于每次迭代,它应该有一秒的间隔。但发生的情况是,当它运行时,它会 hibernate 10 秒,然后 for 循环会像没有 thread.sleep() 时一样运行。
最佳答案
如果这是在 EDT 上完成的(您应该这样做,因为您正在更新 Swing 组件),那么这是因为您阻止了 EDT 10 秒。
考虑使用 Swing 计时器。 https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
class MyActionListener implements ActionListner {
Timer mytimer;
int count;
public void actionPerformed(ActionEvent evt) {
textArea.setText("\n***Iterate***\n");
if( ++count > 10 ) mytimer.stop();
}
};
MyActionListener task = new MyActionListener();
Timer timer = new Timer(1000, task )
task.mytimer = timer;
timer.setRepeats( true );
timer.start();
代码未经测试。
关于java - 线程 hibernate 的工作方式与预期不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50202635/