multithreading - java multithreaded hashed ArrayList<String> -


i want hash on every item arraylist , return on main. example have this:

import java.security.messagedigest; import java.security.nosuchalgorithmexception; import java.util.arraylist;  public class hash extends thread {      private thread t = null;     private messagedigest md = null;     private stringbuffer sb = null;     private string message = null;     private arraylist<string> list = null;     private int count = 0;      public hash(arraylist<string> list) {         this.list = list;     }      public final void mdstart() {          for(string item:list){             this.message=item;             if(t==null){                 t = new thread(this);                 t.start();             }             count++;         }         system.out.println("end: "+this.count);      }      @override     public final void run() {         system.out.println("run: "+this.count);         try {             md = messagedigest.getinstance("md5");             md.update(this.message.getbytes());              byte[] digest = md.digest();             sb = new stringbuffer();             (byte hash : digest) {                 sb.append(string.format("%02x", hash));             }             system.out.println(this.message + " : " + sb.tostring());         } catch (nosuchalgorithmexception ex) {             system.out.println("no such algorithm exception : md5");             system.exit(1);         }     }      public static void main(string args[]) {          arraylist<string> list = new arraylist<>();         (int = 0; < 10; i++) {             list.add("message" + i);         }         new hash(list).mdstart();      }  } 

and out put is:

end: 10 run: 10 message9 : 99f72d2de922c1f14b0ba5e145f06544 

which means program run last 1 thread expect.

you storing thread in t, null @ start after creating first thread, isn't null anymore, if fails , no new thread created. try modify message while thread runs... honestely, whole thing mess. if create 10 threads, point same hash() object message variable changing randomly without knowing if thread has finished working.

for example, following happen:

  1. you start thread first message
  2. thread has not yet run, loop sets message 2nd one
  3. the thread runs , calculates message 2nd message
  4. message 3 set. nothing happens since thread finished.
  5. message 4 set, again, nothing happens thread done etc.

to fix it:

  • remove list variable hash.
  • create new hash() object each hashcode/message
  • start new thread each hash() object. should work.

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

wso2esb - How to concatenate JSON array values in WSO2 ESB? -