This code shows how to manage a thread, i.e. what is the state of a given thread and when all the threads registered with the thread manager has completed
import java.util.*;
import java.io.*;
public class ThreadManager {
static LinkedHashMap linkHashThread = new LinkedHashMap();
static Map m = Collections.synchronizedMap(linkHashThread);
public static synchronized void loadThreadsInit(String tName){
System.out.println("Thread " + tName + "Started");
m.put(tName,"0");
}
public static synchronized void threadCompleted(String tName){
System.out.println("Thread " + tName + "Completed");
m.put(tName,"1");
boolean finalCheck = false;
finalCheck = checkTotalCompletion();
System.out.println("Finla Check " + finalCheck);
if(finalCheck){
// Start--->Add your logic to be called after all the threads are completed
startUpdation();
// End --->Add your logic to be called after all the threads are completed
}
}
/****** Method to be used while using a Linkedhashmap ****/
public static synchronized boolean checkTotalCompletion(){
Set set = m.keySet();
Iterator iter = set.iterator();
String val = "";
while(iter.hasNext()) {
val = (String)m.get(iter.next());
// System.out.print("iter Value " + val + "\t");
if(!val.equals("1"))
return false;
}
return true;
}
public static void startUpdation(){
System.out.println("Table Update started ");
try{
BufferedWriter in1 = new BufferedWriter (new FileWriter("log.txt"));
in1.write("All threads completed ");
in1.close();
}catch(Exception ee){
}
}
}