使用线程输入

nwnhqdif  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(282)
import java.util.Scanner;

public class ThreadClass {

    public static void main(String[] args) 
    {
        System.out.println("Type the following in 5 seconds");
        System.out.println("The quick brown fox jumps over the lazy dog");

        try {
            Scanner sc = new Scanner(System.in);
            String str=sc.nextLine();
            Thread.sleep(1000);
            System.out.println("Your time is over");

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

在上面的程序中,我希望我的程序应该要求用户在5秒(或5000毫秒)内输入,并且应该在时间结束后自动关闭并显示一条消息“您的时间结束了”。这段代码的问题在于,每当用户输入内容时,除非按下enter键,否则线程似乎不起作用。我试过在try-catch块外甚至线程下写扫描器代码,但似乎都不起作用。我认为问题出在我的scanner类上,但我无法解决如何以其他方式输入数据。

2nbm6dog

2nbm6dog1#

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class Test {
    static volatile boolean isTimeCopleted = true;

    public static void main(String[] args) {
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                if (isTimeCopleted) {
                    System.out.println("Your time is over");
                    System.exit(0);
                }
            }
        };
        timer.schedule(task, 5000);

        System.out.println("Type the following in 5 seconds");
        System.out.println("The quick brown fox jumps over the lazy dog");

        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        isTimeCopleted = false;

        System.out.println("Process Done");
        System.exit(0);
    }
}
fnvucqvd

fnvucqvd2#

如果您的唯一动机是检查用户是否在5秒内插入了输入,那么为什么不通过计算时间来尝试这段代码呢

Scanner sc = new Scanner(System.in);
        long begantime = System.nanoTime();
        System.out.println("Enter something");
        String input = sc.nextLine();
        int totalTime = (System.nanoTime()-beganTime)/1000000000;
        if (time > 5)
            System.out.println("failed");
        else
            System.out.println(input);
a0zr77ik

a0zr77ik3#

只是一个提示:您必须有两个线程-一个用于输入,另一个用于计时器。一旦计时器过期,中断输入线程。例如:

final Thread subject1 = new Thread(new Runnable() {

  public void run() {
    while (!Thread.interrupted()) {
      Thread.yield();
    }
    System.out.println("subject 1 stopped!");
  }
});
final Thread subject2 = new Thread(new Runnable() {

  public void run() {
    while (!Thread.interrupted()) {
      Thread.yield();
    }
    System.out.println("subject 2 stopped!");
  }
});
final Thread coordinator = new Thread(new Runnable() {

  public void run() {
    try {
      Thread.sleep(500);
    } catch (InterruptedException ex) { }
    System.out.println("coordinator stopping!");
    subject1.interrupt();
    subject2.interrupt();
  }
});
subject1.start();
subject2.start();
coordinator.start();

相关问题