multithreading - Java concurrency -_- visibility/reordering when sharing vars between threads -


i'm taking first steps learning multithreading, , build little test program in order create insight myself. i'm not convinced solution safe because of reordering possibility..

this main program:

public class synchtest {      private static sychint = new sychint();     private static sychbool b = new sychbool();      public static void main(string[] args) {         system.err.println("begin");         b.setb(false);         i.seti(100);          // create 100 dra threads         (int = 0; < 1000; i++) {             new dra().start();         }          // should these lines synched in case of reordering? if so, how to?         i.seti(200);         b.setb(true);      }      private static class dra extends thread {         @override         public void run() {              // wait main thread set b = true             while (!b.getb()) {                 dra.yield();             }              // should 200 in case of correct synchronisation             if (i.geti() != 200) {                 system.err.println("oh noes! " + i.geti());             } else {                 // system.out.println("synch working!");             }          }     }  } 

and these classes, sychint:

public class sychint {      private int = 0;      public synchronized void seti(int i){         this.i = i;     }      public synchronized int geti (){         return this.i;     }  } 

sychbool:

public class sychbool {     private boolean b;      public synchronized boolean getb() {         return b;     }      public synchronized void setb(boolean b) {         this.b = b;     }   } 

any advice/reassurance helpfull!

thnx,

newbie multithreading :)

// should these lines synched in case of reordering? if so, how to? i.seti(200); b.setb(true); 

in case fine.

b.setb(true) cannot reordered above i.seti(200). normalstore , monitorenter cannot ordered above monitorexit. in case monitor exit happens @ end of seti, followed monitor enter , normal store (of setb), reorder not possible here.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

mysql - Pass value between different pages (form) with PHP -