Weird multithreading behaviour (Java) -


just messing around multithreading learn more regards synchronized keyword , other aspects wrote simple class , main class call methods of class in different threads. saw expecting few times (values changing 2 instead of 1) came across larger jump can't understand - know how happened?

here's code:

public class seatcounter {     private int count = 0;      public  int getseatcount() {         return count;     }      public  void bookseat() {         count++;     }      public  void unbookseat() {         count--;     } } 

and

public class main {     public static void main(string args[]) {         final seatcounter c = new seatcounter();          thread t1 = new thread() {             public void run() {                 while(true) {                     c.bookseat();                     system.out.println(c.getseatcount());                 }             }         };          thread t2 = new thread() {             public void run() {                 while(true) {                     c.unbookseat();                     system.out.println(c.getseatcount());                 }             }         };          t1.start();         t2.start();     } } 

and got @ point in console:

-16066 -16067 -16068 -16069 -16031 -16069 -16068 -16067 -16066 

edit: swift replies, know using synchronized, playing around see went wrong, thing don't understand how changed jump of (-16069 -16031) in 1 jump, since printout statement should happen every change of stored value , 2 threads running without synchronization would've assumed mean @ jump of 2 in value.

there 2 things cause "strange" counts.

  • it entirely possible count++, count-- calls fail work expected: since count++ requires count value read, , incremented (internally: 2 operations), other thread can mess around values after have read them before have changed-and-stored them, leading modify-after-read data race. can solve synchronization or use of atomicinteger.
  • you have no guarantees regarding when code execute. in particular, thread1 may finish before thread2 starts, or vice-versa, or both may take weird turns. operating system free allocate processor time threads sees fit (and in multi-core machines, can execute in parallel). long there 1 thread generating output, not notice such things; there constant churn of threads starting, executing, being pre-empted, running again, , on while computer working; managed operating systems' scheduler.

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -