Threading and synchronized methods

前端 未结 3 2029
甜味超标
甜味超标 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条回答
  •  囚心锁ツ
    2021-01-21 13:04

    The lock used by synchronized methods is associated with an instance of class MyThread. Since each thread has its own instance MyThread, each thread is synchronizing on its own lock.

    If you wanted to synchronize across all threads, you could do something along the lines of:

    public class MyThread extends Thread {
    
        private static final Object sharedLock = new Object();
    
        public void doSomething() {
          synchronized(sharedLock) {
            for(int i=0; i<100000; i++) {
              System.out.println(this.i);
            }
          }
        }
        ...
     }
    

    An alternative is to synchronize on MyThread.class, but I prefer the first approach.

    In the comments you say that if you change your code to use synchronized(this) in doSomething, all of a sudden it works. I am pretty sure it doesn't. It may have worked by chance, but it won't work repeatedly and reliably.

提交回复
热议问题