java - How to terminate a particular blocking thread -


scenario: have limited number of independent tasks given few threads finish tasks. main thread should wait threads finish tasks. while works of time, 1 of threads can't finish tasks , main thread waits indefinitely. how possible kill blocked thread?

here sample code explains scenario.

client class

public class threadstop {  public static void main(string[] args){      list<thread> threadlist = getmythreadlist();              (thread thread : threadlist) {         thread.start();     }      system.out.println("waiting child threads die");      (thread thread : threadlist) {         try {             thread.join();             system.out.println(thread.getname() + " finished job");                      } catch (interruptedexception e) {             system.out.println("interrupted exception thrown : "                     + thread.getname());                         }     }      system.out.println("all child threads finished 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 thread "+      thread.currentthread().getname());         }  } 

note please note can't use executor framework.

if tasks explicitly written subclassing thread directly, using executor framework out[1]. in case should use join() timeout value. if join not succeed, can interrupt() thread (but that's not guaranteed 'kill'). poking threads directly not nice way of doing things -- it's game in lose, winning move not play.

however if tasks written more sanely/with benefit of modern insights, can @ least wrapped runnable (or indeed, runnable , passed constructor of thread). @ point can use executor framework again.

  1. although could pass instances of thread executor directly, provided can avoid calling start() or run() threads elsewhere in code (because if other code executes same task, task executed twice in best-case scenario).

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -