简体   繁体   English

如何启动线程但保持一段时间?

[英]How do I start a Thread but keep it alive for a certain time?

I don't really want to start a thread then put it to sleep, such as: 我真的不想开始一个线程然后让它进入睡眠状态,例如:

Thread.start();
Thread.sleep(3000);  //*Example* 

Instead, I want to this something like this (And I apologize for this amateur illustration): 相反,我想这样的事情(我为这个业余插图道歉):

Thread.start(3000) //*thread will be given a certain amount of time to execute* 

 //*After 3000 milliseconds, the thread stops and or sleeps*

I'm doing this because I'm making a program/ mini-game that times user input for a certain time. 我这样做是因为我正在制作一个程序/迷你游戏,用户输入一段时间。 Basically, the user has 5 seconds to input a certain character/number/letter and after that time, the input stream is cut off. 基本上,用户有5秒钟输入某个字符/数字/字母,在此之后,输入流被切断。 Kind of like: 有一些像:

Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
kb.close()    //*Closes kb and input stream in turn*

I suggest you use a ScheduledExecutorService and scheduleWithFixedDelay(Runnable, long, long, TimeUnit) . 我建议你使用ScheduledExecutorServicescheduleWithFixedDelay(Runnable, long, long, TimeUnit) You can cancel that if the user completes whatever task before the delay expires. 如果用户在延迟到期之前完成任何任务,您可以取消该操作。 If the delay runs out then the user failed whatever task. 如果延迟用完,则用户失败了任何任务。

You can try this sample. 你可以尝试这个样本。

    final List<Integer> result = new ArrayList<>();
    Thread thread = new Thread() {
        volatile boolean isDone = false;
        Timer timer = new Timer();

        @Override
        public void run() {
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isDone = true;
                }
            }, 5000);

            Scanner kb = new Scanner(System.in);
            while (!isDone) {
                int num = 0;
                num = kb.nextInt();
                result.add(num);
            }
            kb.close();
        }

    };
    thread.start();
    thread.join();

    for (Integer i : result) {
        System.out.print(i + " ");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM