[英]Interrupt sleep in a single thread
我想在Java中實現代碼的停止點,以便在20秒內不執行任何操作,除非用戶按Enter。 目前,我僅使用:
sleep(20000);
我知道一個線程可以被使用wait()
和notify()
的另一個線程“喚醒”,但是我想知道是否存在不需要拋出新線程的事情。 理想情況下,我希望能夠向鍵盤上的InputStream的讀取操作添加超時,以便可以執行以下操作:
try {
//Here is where the waiting happens
myStream.read();
} catch (TimeoutException e) { }
//... Continue normally
您可以不睡眠20秒,而應間隔1秒睡眠,然后輪詢以查看用戶是否輸入了任何內容:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 20; i++) {
try {
sleep(1000);
if (in.ready()) {
break;
} else {
System.out.println(i+" seeconds have passed");
}
} catch (InterruptedException | IOException ex) {
}
}
這些評論是正確的,但建議采取一種(有點hacky)的解決方法:
BufferedReader myStream = new BufferedReader(new InputStreamReader(System.in));
long startTime = System.currentTimeMillis();
while(System.currentTimeMillis() < (startTime + 20000)) {
if (myStream.ready()) {
//do something when enter is pressed
break;
}
}
超時中斷的阻塞讀取無法使用一個線程完成,因為對輸入流的讀取會無限期阻塞。 有一種方法可以使用Future使用超時執行計算,但這首先涉及並發編程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.