簡體   English   中英

如何啟動線程但保持一段時間?

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

我真的不想開始一個線程然后讓它進入睡眠狀態,例如:

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

相反,我想這樣的事情(我為這個業余插圖道歉):

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

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

我這樣做是因為我正在制作一個程序/迷你游戲,用戶輸入一段時間。 基本上,用戶有5秒鍾輸入某個字符/數字/字母,在此之后,輸入流被切斷。 有一些像:

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

我建議你使用ScheduledExecutorServicescheduleWithFixedDelay(Runnable, long, long, TimeUnit) 如果用戶在延遲到期之前完成任何任務,您可以取消該操作。 如果延遲用完,則用戶失敗了任何任務。

你可以嘗試這個樣本。

    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