如何在Thread完成后继续进行For循环?

时间:2017-05-26 16:11:04

标签: java multithreading for-loop java.util.scanner thread-sleep

使用线程

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

答案 0 :(得分: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);
    }
}