简体   繁体   中英

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. 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) . 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 + " ");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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