有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    你不需要等待其他线程的答案。这是如何使用单个线程完成的:

    public class FastMath {
    
        public static void main(String[] args) throws IOException {
            int answer;
    
            System.out.println("How many questions can you solve?");
    
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    
            int total = Integer.valueOf(in.readLine());
    
            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 + " = ");
    
                long startTime = System.currentTimeMillis();
                while ((System.currentTimeMillis() - startTime) < 3 * 1000
                        && !in.ready()) {
                }
    
                if (in.ready()) {
                    answer = Integer.valueOf(in.readLine());
    
                    if (answer == n1 * n2)
                        right++;
                    else
                        wrong++;
                } else {
                    missed++;
                    System.out.println("Time's up!");
                }
            }
            System.out.printf("Results:\n\tCorrect answers: %d\n\nWrong answers:%d\n\tMissed answers:%d\n", right, wrong, missed);
        }
    }