Threading and synchronized methods

前端 未结 3 2035
甜味超标
甜味超标 2021-01-21 12:24

I have the following code:

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


         


        
3条回答
  •  梦毁少年i
    2021-01-21 13:06

    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.

提交回复
热议问题