java - Argument state after the thread is completed -


question:

suppose pass arraylist runnable constructor. in runnable class add strings list. run thread main() , wait completion. after thread execution over, possible when iterate list in main() strings(values) added list runnable class because reference arraylist created in heap. when iterate list, empty. explain why list empty.

thanks in advance: vijay k

public class getlistthread implements runnable{  private list<string> names;  public getlistthread(list<string> names) {     super();     this.names = names; }  @override public void run() {      for(int i=0;i<4;i++){         try {             names.add(threadlocalrandom.current().nextint(1,10) + "a");             thread.sleep(2000);         } catch (interruptedexception e) {             e.printstacktrace();         }     }      //system.out.println(names); } }   public class testthread {  public static void main(string[] args) {      list<string> names = new arraylist<string>();      getlistthread g = new getlistthread(names);     thread t = new thread(g);      t.start();     system.out.println(t.getstate());      for(string s : names){         system.out.println(s);     } } } 

after thread execution over, possible when iterate list in main() strings(values)

yes, collection not thread safe, there no guarantee ever see anything. might see null values i.e. size correct elements not.

could explain why list empty.

however in case, not waiting, there no chance have elements.

the thread takes time start, highly unlikely see first element added.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -