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循环的下一次迭代。

+0

您是否必须为此使用'Thread'?还有其他解决方案可能更容易实施。 – KDecker

+0

扩展'Runnable',而不是'Thread'。不要同步'run'方法。研究如何处理'InterruptedException',这里你不这样做。摆脱冗余的'return'和'continue'语句。您的主线程不会等待计时线程,因此后者不起作用。线程不共享信息,因此主线程无法判断时间限制是否被违反。 –

回答

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); 
    } 
}