java - Multithreading not working as expected -


i trying test couple of things regards iterators being shared across multiple threads. wrote simple (and quite stupid) program supposed iterate through same map intwo different threads. here's code:

    final map<integer, integer> m = new hashmap<integer, integer>();     final random r = new random();     for(int = 0; i< 1000 ; i++){         m.put(r.nextint(10000), r.nextint(10000));     }     thread t1 = new thread(new runnable(){          @override         public void run() {             // todo auto-generated method stub             iterator<integer> = m.keyset().iterator();             it.next();             for(integer : m.keyset()){                 system.out.println("t1  " + i);                 try {                     thread.sleep(r.nextint(100));                 } catch (interruptedexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 }             }         }      });      thread t2 = new thread(new runnable(){          @override         public void run() {             // todo auto-generated method stub             iterator<integer> = m.keyset().iterator();             it.next();             for(integer : m.keyset()){                 system.out.println("t2  " + i);                 try {                     thread.sleep(r.nextint(100));                 } catch (interruptedexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 }             }         }      });      t1.run();     t2.run(); 

now, when run expecting either exception of concurrent modification of sort, or mixture of both "t1 " , "t2 " messages in console. happens program outputs values map thread 1 , progresses thread 2. why serializable behaviour case here?

you need call t1.start() , t2.start() rather run.

calling run execute code run method.
start launches new thread.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -