multithreading - Java threading issue? -


i wondering why result not 400 000. there 2 threads why gets blocked?

class intcell {     private int n = 0;     public int getn() {return n;}     public void setn(int n) {this.n = n;} } class count extends thread {     private static intcell n = new intcell();     @override public void run() {         int temp;         (int = 0; < 200000; i++) {             temp = n.getn();             n.setn(temp + 1);         }     }     public static void main(string[] args) {         count p = new count();         count q = new count();         p.start();         q.start();         try { p.join(); q.join(); }         catch (interruptedexception e) { }         system.out.println("the value of n " + n.getn());     } } 

why there problem that?

when 2 threads access 1 object @ same time, interfere each other, , result not deterministic. example, imagine p reads value of n , gets, say, 0, q reads same value , gets 0 too, p sets value 1 , q sets 1 (because still thinks has value 0). value of n increased 1, though both counters "incremented" once. need use synchronized block make sure counters won't interfere each other. see https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html more.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -