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.
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.
The synchronization on methods only holds for invocations of the same object. You are creating two different objects (the two threads).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With