0
線程使用利用上述螺紋線程完成後,如何讓此循環繼續?
public class MissedThread extends Thread
{
public synchronized void run()
{
try
{
Thread.sleep(1000);
System.out.println("Too slow");
}catch(InterruptedException e){return;}
}
}
方案
import java.util.Scanner;
public class FastMath
{
public static void main(String[] args)
{
System.out.println("How many questions can you solve?");
Scanner in = new Scanner(System.in);
int total = in.nextInt();
MissedThread m = new MissedThread();
int right = 0;
int wrong = 0;
int missed = 0;
for(int i = 0;i<total;i++)
{
int n1 = (int)(Math.random()*12)+1;
int n2 = (int)(Math.random()*12)+1;
System.out.print(n1+" * "+n2+" = ");
m.start();
int answer = in.nextInt();
if(answer==n1*n2)
{
right++;
continue;
}
if(answer!=n1*n2)
{
wrong++;
continue;
}
}
}
}
所以該程序的目的是,如果用戶不1秒(Thread.sleep代碼的持續時間)內輸入一個數字,它會打印一條消息並繼續進行下一次迭代。但是,如果及時回答,它會停止該程序。如果它沒有及時得到答案,它似乎會卡住,而不會移動到for循環的下一次迭代。
您是否必須爲此使用'Thread'?還有其他解決方案可能更容易實施。 – KDecker
擴展'Runnable',而不是'Thread'。不要同步'run'方法。研究如何處理'InterruptedException',這裏你不這樣做。擺脫冗餘的'return'和'continue'語句。您的主線程不會等待計時線程,因此後者不起作用。線程不共享信息,因此主線程無法判斷時間限制是否被違反。 –