需要停止或终止线程

时间:2014-03-11 09:29:53

标签: java threadpool

因为我编写了一个简单的Java程序来调用Thread。下面是我的代码

public class ThreadPoolForParallelExec {

    public static void main(String args[]) {
        ExecutorService service = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            service.submit(new Task(i));
        }
        service.shutdown();
    }
}

final class Task implements Runnable {
    private int taskId;

    public Task(int id) {
        this.taskId = id;
    }

    @Override
    public void run() {
        myclient.intializeAndConnectRemoteMachine(taskId);
        Thread.currentThread().stop();
        Thread.currentThread().isInterrupted();
    }
}

但是,我需要终止Executor或Thread。我试过Thread.currentThread()。stop();和 Thread.currentThread()停止()。两个都没有工作:(你能不能满意。

6 个答案:

答案 0 :(得分:1)

一般来说,kill线程是一个坏主意,事实上,最新的Java规范也不赞成。

相反,尝试在线程本身内优雅地完成线程。这是一贯的结构。

答案 1 :(得分:1)

让方法正常结束。

然后线程将处于空闲状态,ExecutorService将在之后关闭。

答案 2 :(得分:0)

永远不要使用Thread.stop。它已被弃用:

来自JLS:

  

这种方法本质上是不安全的。使用Thread.stop停止一个线程会导致它解锁它已锁定的所有监视器(这是未经检查的ThreadDeath异常向上传播的自然结果)。如果先前受这些监视器保护的任何对象处于不一致状态,则受损对象对其他线程可见,可能导致任意行为。 stop的许多用法应该被简单修改某个变量的代码替换,以指示目标线程应该停止运行。目标线程应该定期检查此变量,并且如果变量指示它将停止运行,则以有序的方式从其run方法返回。如果目标线程等待很长时间(例如,在条件变量上),则应该使用中断方法来中断等待

执行此操作的好方法是让线程的run()由boolean变量保护,并在您想要停止时从外部将其设置为true。

确保你已经保护boolean字段volatile以确保阅读主题看到写作线程的变化。

答案 3 :(得分:0)

我认为你应该调用interrupt()然后等待Threads完成。然后,您可以在不运行线程的情况下执行任何操作。

答案 4 :(得分:0)

你可以使用Thread.interrupt()或在run方法中使用volatile标志,并在你想要停止线程时将其设置为false。

@Override
public void run() {
    while (running) {
        try {
            ....
        } catch (InterruptedException e) {

            running = false;
        }
    }
}

运行时,标志初始化为true。

有关详细信息,请参阅this link

答案 5 :(得分:0)

1.5版的文档说:

interrupt

public void interrupt()
Interrupts this thread.

Unless the current thread is interrupting itself, which
is always permitted, the checkAccess method of this thread
is invoked, which may cause a SecurityException to be thrown.

If this thread is blocked in an invocation of the
wait(), wait(long), or wait(long, int) methods of the
Object class, or of the join(), join(long), join(long,
int), sleep(long), or sleep(long, int), methods of this
class, then its interrupt status will be cleared and it
will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an
interruptible channel then the channel will be closed,
the thread's interrupt status will be set, and the
thread will receive a ClosedByInterruptException.

If this thread is blocked in a Selector then the
thread's interrupt status will be set and it will
return immediately from the selection operation,
possibly with a non-zero value, just as if the
selector's wakeup method were invoked.

If none of the previous conditions hold then this
thread's interrupt status will be set.

Throws:
SecurityException - if the current thread cannot modify this thread