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'语句。您的主线程不会等待计时线程,因此后者不起作用。线程不共享信息,因此主线程无法判断时间限制是否被违反。 –