Scenario: I have a limited number of independent tasks which will be given to few threads to finish those tasks. The main thread should wait for all the threads to finish their tasks. While it works for most of the time, sometimes one of the threads can't finish its tasks and so the main thread waits indefinitely. How is it possible to kill that blocked thread?
Here is the sample code which explains the scenario.
Client Class
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;
}
}
Thread class
public class MyThread implements Runnable{
@Override
public void run() {
System.out.println("hello world by thread "+ Thread.currentThread().getName());
}
}
Note Please note that I can't use executor framework.