如何终止特定的阻塞线程

时间:2015-11-01 14:01:17

标签: java multithreading

场景:我有一些有限的独立任务,这些任务将被提供给几个线程来完成这些任务。主线程应等待所有线程完成其任务。虽然它在大多数情况下都有效,但有时其中一个线程无法完成其任务,因此主线程无限期地等待。如何杀死被阻止的线程?

以下是解释该方案的示例代码。

客户等级

public class ThreadStop {

public static void main(String[] args){

    List<Thread> threadList = getMyThreadList();        

    for (Thread thread : threadList) {
        thread.start();
    }

    System.out.println("Waiting for Child Threads to die");

    for (Thread thread : threadList) {
        try {
            thread.join();
            System.out.println(thread.getName() + " Finished its job");             
        } catch (InterruptedException e) {
            System.out.println("Interrupted Exception thrown by : "
                    + thread.getName());                
        }
    }

    System.out.println("All Child Threads Finished their Job");
}

private static List<Thread> getMyThreadList() {
    List<Thread> threadList = new ArrayList<>();
    MyThread myThread;
    Thread thread;
    for(int i=0; i<10; i++){
        myThread = new MyThread();
        thread = new Thread(myThread);
        thread.setName("Thread "+i);
        threadList.add(thread);
    }
    return threadList;
}
}  

主题类

public class MyThread implements Runnable{

@Override
public void run() {
    System.out.println("hello world by thread "+      Thread.currentThread().getName());        
}

}

注意请注意,我不能使用执行器框架。

1 个答案:

答案 0 :(得分:0)

如果任务直接显式写为子类Thread,那么使用Executor框架就是[1]。在这种情况下,您应该使用具有超时值的join()。如果加入不成功,您可以interrupt()该帖子(但这不是保证&#39; kill&#39;)。直接戳线并不是一种很好的做事方式 - 它就像一场你总是输球的比赛,唯一的胜利就是不打比赛。

然而,如果任务写得更加明智/有利于现代见解,那么它们至少可以包含Runnable(或者实际上,它们是Runnable并且只是传递给Thread)的构造函数。此时,您可以再次使用Executor框架。

  1. 虽然你可以直接将Thread的实例传递给Executor,前提是你可以避免在代码中的其他位置调用start()run()线程(因为如果其他代码也执行相同的任务,然后在最佳情况下执行两次任务。)
相关问题