简体   繁体   中英

How do you stop a thread in a Java command prompt that is stopped when the user commands it to stop?

Basically, I have a Java thread that is running in a console that will go infinitely, unless the user enters "halt", the program should stop the thread and stop the console.

Here's what the set_interval part of the thread kind of looks like (the user can give an input of how long of an interval they want in between threads):

public void set_interval(int mins, int secs) {
    time = (mins * 60000) + (1000 * secs);
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {
            try {
                count += counter;
                String name = getName();
                Date date = new Date();
                System.out.print("\n" + "Thread:" + name + " " + date + " - counter: " + count);
                Thread.sleep(time);
            } catch(InterruptedException e){
                System.out.print(e);
            }
    }, 0, time);    
}

and here's kind of what main looks like: }else if (checkLine.equals("halt")){ Thread test = new Thread("name"); test.interrupt(); break; } }else if (checkLine.equals("halt")){ Thread test = new Thread("name"); test.interrupt(); break; }

Every where I look says to use interrupt, but this interrupt doesn't seem to work. Anyone got any ideas? Or am I just overlooking some small details? There's a chance that I need to use sockets to solve this problem.

interrupt only interrupts the thread you interrupt. In your code you create thread which you interrupt, but no other thread will be effected.

You could interrupt the thread in the Timer except you log the interrupt but continue as if it didn't happen ie it won't stop the thread.

I would use a ScheduleExecutorService for this as it supports shutdownNow() which stops the thread pool and interrupts all the running tasks.

Take a look at ScheduledExecutorService , which can be used to manage your tasks. Using an executor service makes multithreaded live easier in Java :)

Why not move the timer out of the function and into the class-scope? And then call timer.purge() or timer.cancel() ? - BUT HOLD ON! They only stop/cancel all the non-active tasks. The currently executing task will NEVER be stopped.

You're trying to stop a currently executing task. An easier way is : to have an AtomicBoolean dontKeepRunning variable which you set to true when you want the task has to be terminated.

Like this:

private AtomicBoolean dontKeepRunning;
public YourTimerTask(){ dontKeepRunning = new AtomicBoolean();}
public void halt()
{
     dontKeepRunning.set(true);
}
public void set_interval(int mins, int secs) {
    time = (mins * 60000) + (1000 * secs);
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {
            try { 
                count += counter;
                String name = getName();
                Date date = new Date();
                System.out.print("\n" + "Thread:" + name + " " + date + " - counter: " + count);
                while(dontKeepRunning.get() == false){}
                return;
            } catch(InterruptedException e){
                System.out.print(e);
            }
    }, 0, time);    
}

Issue Thread.interrupt on all your threads. And these threads must support interruption . Basically the threads must:

  1. Test for interruption flag from time to time, for example with Thread.currentThread.isInterrupted()
  2. Finish on receiving InterruptedException

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