javamultithreadinglinked-listself-destruction

Can this reference in run() refer to Thread object when implementing Runnable?


Sorry if the question is unclear

I am making a simple multithread program that has a linked list to store all thread created except the main thread. Then I want to send some signal to terminate the main thread but only when all other threads have closed and I intend to do this by making that when the thread close, it will remove itself from linked list then the main thread will check if that list size == null or not

here is my 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 for all 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 the main will check the threadList if it is null. The problem is I don't know how to make the thread remove itself from the list. As what I have searched, for normal object, I can create method like this

public class someObject {
    public static void delete(){
        if(list.size = null) return;
        list.remove(this);
    }
}

However, in case of thread, the Class implement Runnable so this reference is to the object but not the thread stored in the list


Solution

  • I would recommend using a HashMap instead of a List. The keys can be the Thread Name (e.g. Thread.getName()) and the values will be the Threads.

    Map<String, Thread> threadMap = new HashMap<String, Thread>();
    

    You should also create this Map as a synchronizedMap (using Collections.synchronizedMap(...))

    Map<String, Thread> synchronizedMap = Collections.synchronizedMap(threadMap);
    

    Now, whenever you construct a Thread, you pass this HashMap into its constructor and the Thread can hold a reference to it. Therefore, when the Thread is about to terminate it can remove itself from the HashMap by using its own Thread name as the key to remove.