multithreading - Synchronization Fail in Java -


from the tutorial read:

it not possible 2 invocations of synchronized methods on same object interleave. when 1 thread executing synchronized method object, other threads invoke synchronized methods same object block (suspend execution) until first thread done object.

however, in simple example there still race competition access message object.

public class testthread extends thread{     int thread;     stringbuilder message;      public testthread(int thread, stringbuilder message) {         this.thread=thread;         this.message=message;         start();     }      public void run() {         synchronized(this){             (int i=0; i<1000000; i++) {                 double a=2*2;             }             modifymessage();         }     }      public synchronized void modifymessage() {         message.append(thread);     } }  public class testmultithreading {     static testthread[] testthreads = new testthread[5];      public static void main(string args[]) {         stringbuilder message = new stringbuilder("a");         (int i=0;i<5;i++)             testthreads[i] = new testthread(i, message);         (int i=0;i<5;i++)             try {                 testthreads[i].join();             } catch (interruptedexception e) {}         out.println(message);     } } 

i expect have guaranteed output of string of length 6. however, time time see this:

a1034 

this means 1 of threads failed modify object. can explain me, why happens , propose solution problem?

you answered own question:

when 1 thread executing synchronized method object, other threads invoke synchronized methods same object block

the synchronized block access on method of same object, means in every thread modifymessage() can called @ same time

what looking this:

   (int i=0; i<1000000; i++) {        double a=2*2;    }    synchronized(message){        modifymessage();    } 

now method call once per stringbuilder instance.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -