java - Can this reference in run() refer to Thread object when implementing Runnable? -
sorry if question unclear
i making simple multithread program has linked list store thread created except main thread. want send signal terminate main thread when other threads have closed , intend making when thread close, remove linked list main thread check if list size == null or not
here code
public class mainprogram { //some global static variable static list<thread> threadlist = new linkedlist<thread>(); public void main() throws ioexception { serversocket serversocket; serversocket = new serversocket(1234); while(true){ if(shutdown_handler.shutdown==true){ //wait other thread close/terminate return } socket s = serversocket.accept(); clientthread x = new clientthread(s); thread y = new thread(x); threadlist.add(y); y.start(); } } }
when shutdown_handler.shutdown==true main check threadlist if null
. problem don't know how make thread remove list. have searched, normal object, can create method this
public class someobject { public static void delete(){ if(list.size = null) return; list.remove(this); } }
however, in case of thread, class implement runnable
this
reference object not thread stored in list
i recommend using hashmap
instead of list
. keys can thread name (e.g. thread.getname()
) , values threads.
map<string, thread> threadmap = new hashmap<string, thread>();
you should create map synchronizedmap (using collections.synchronizedmap(...)
)
map<string, thread> synchronizedmap = collections.synchronizedmap(threadmap);
now, whenever construct thread, pass hashmap constructor , thread can hold reference it. therefore, when thread terminate can remove hashmap
using own thread name key remove.