简体   繁体   English

如何在用户命令停止的Java命令提示符中停止线程?

[英]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. 基本上,我有一个在控制台中运行的Java线程,它将无限循环运行,除非用户输入“ halt”,否则程序应停止线程并停止控制台。

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): 这是线程的set_interval部分的样子(用户可以输入他们希望在线程之间间隔多长时间的输入):

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; } }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. 我将为此使用ScheduleExecutorService,因为它支持shutdownNow() ,它可以停止线程池并中断所有正在运行的任务。

Take a look at ScheduledExecutorService , which can be used to manage your tasks. 看一看ScheduledExecutorService ,它可以用来管理您的任务。 Using an executor service makes multithreaded live easier in Java :) 使用执行程序服务使Java中的多线程生存更加容易:)

Why not move the timer out of the function and into the class-scope? 为什么不将计时器移出函数并移入类范围? And then call timer.purge() or timer.cancel() ? 然后调用timer.purge()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. 一种更简单的方法是:拥有一个AtomicBoolean dontKeepRunning变量,当您希望任务必须终止时将其设置为true。

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. 在所有Thread.interrupt上发出Thread.interrupt 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() 不时测试中断标志,例如使用Thread.currentThread.isInterrupted()
  2. Finish on receiving InterruptedException 完成接收InterruptedException

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

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