Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading and synchronized methods

I have the following code:

public class MyThread extends Thread {
    private int i;
    public static int sum=0;
    public MyThread(int k){
      i=k;
    }




    public static void main(String[] args) throws InterruptedException{

       Thread t=new MyThread(1);
       Thread s=new MyThread(2);
       Thread p=new MyThread(3);
       t.start();
       s.start();       
    }


public synchronized void doSomething(){
    for(int i=0; i<100000; i++){
        System.out.println(this.i);
    }

}

    @Override
    public void run() {
        doSomething();

    }
}

the doSomething is synchronized. why is the output random? My assumption that the synchronized method would be the same as the synchronized block but the output of the block is sync and the method isn't.

like image 370
mary Avatar asked Sep 17 '26 08:09

mary


2 Answers

The synchronized keyword there prevents synchronized method calls on the same object from being interleaved. It does not prevent interleaving method calls on different objects. Since you have three different objects, the three calls can run simultaneously.

You need to synchronize on a single object which is shared by all three threads.

like image 87
Mark Byers Avatar answered Sep 18 '26 22:09

Mark Byers


The synchronization on methods only holds for invocations of the same object. You are creating two different objects (the two threads).

like image 27
decden Avatar answered Sep 18 '26 21:09

decden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!