java如何在线程完成后使For循环继续?
使用的线程
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循环的下一个迭代
# 1 楼答案
你不需要等待其他线程的答案。这是如何使用单个线程完成的: