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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | 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){ } } } |