Why is Java synchronized not working as expected?

前端 未结 3 1174
名媛妹妹
名媛妹妹 2021-01-24 06:38

I\'m trying to figure out how synchronized methods work. From my understanding I created two threads T1 and T2 that will call the same method <

相关标签:
3条回答
  • 2021-01-24 07:25

    try this :

    public class Main {
        public static void main(String[] args) {
            A a = new A();
            Thread t1 = new Thread(a);
            Thread t2 = new Thread(a);
            t1.setName("T1");
            t2.setName("T2");
            t1.start();
            t2.start();
        }
    }
    
     class B {
        public synchronized void addNew(int i){
            Thread t = Thread.currentThread();
            for (int j = 0; j < 5; j++) {
                System.out.println(t.getName() +"-"+(j+i));
            }
        }
    }
    
     class A extends Thread {
        private B b1 = new B();
    
        @Override
        public void run() {
            b1.addNew(100);
        }
    }
    
    0 讨论(0)
  • 2021-01-24 07:43

    Both A objects have their own B object. You need them to share a B so the synchronization can have an effect.

    0 讨论(0)
  • 2021-01-24 07:45

    Each A instance has its own B instance. The method addNew is an instance method of B. Therefore, the lock acquired implicitly during calls to addNew is the lock on the receiver B instance. Each thread is calling addNew on a different B, and therefore locking on different locks.

    If you want all B instances to use a common lock, create a single shared lock, and acquire it in the body of addNew.

    0 讨论(0)
提交回复
热议问题