我試圖通過調用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