java thread runnable sleep_java – 如何在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()方法的整个想法是暂停执行.

编辑以回应Philipp的评论

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方法显示一组没有延迟的jlabel,当我不包含你刚才提到的让线程进入休眠状态的代码时.但是,当我包含使线程进入休眠状态的代码时,图像的显示也会延迟两秒,这很奇怪,因为Thread.sleep()在显示图像后执行.

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页