我试图通过调用Thread类的sleep()
方法来暂停执行部分程序几秒钟。但是,当我尝试这样做时,在调用之后立即执行的代码仍然立即执行。例如,如果我有代码:如何在Thread的sleep()方法立即执行后停止代码
Thread compoundThread = new Thread(new Runnable()
{
public void run()
{
try
{
Thread.currentThread().sleep(2000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
Thread.currentThread().interrupt();
}
}
});
compoundThread.start();
System.out.println("line 15")
第15行只是立即打印。有没有解决这个问题的方法?我认为sleep()
方法的全部想法是暂停执行。
编辑回应菲利普的评论
while (totalNoOfPhase1Trials > 399)
{ //
Phase1Trial phase1Trial = new Phase1Trial(numberOfElements, elementColors);
displayComplexStimulus(phase1Trial.getComplexStimulus());
validate();
Thread compoundThread = new Thread(new Runnable(){
public void run() {
try {
Thread.currentThread().sleep(2000);
System.out.println("line 226");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
}
});
compoundThread.start();
try {
compoundThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
的displayCompoundStimulus
方法显示无延迟的时候,我不包括你刚才提到的,我把线程睡眠代码一套jlabels
。但是,当我包含使线程进入睡眠状态的代码时,图像的显示也会延迟两秒,这很奇怪,因为在显示图像后执行Thread.sleep()
。
能否请您包括行号为您的代码 – amith
我不知道怎么样,但的System.out.println(“线15“)是行15. – lb91
线程将在另一个执行上下文中执行;你期望什么? – fge