Java多线程-01[锁对象改变导致异步执行]

先来看这样一段代码

MyThread.java

public class MyThread extends Thread {
    @Override
    public void run() {
        A.staticMethod();
    }

    public static void main(String[] args) {
        MyThread myThread1 = new MyThread();
        MyThread myThread2 = new MyThread();
        myThread1.start();
        myThread2.start();
    }
}

A.java

package com.dronff.mt;

/**
 * @author tyf
 * 2022/5/20
 */
public class A {
    private static String a = "123";
    public static void staticMethod(){
        synchronized (a) {
            a="444";
            System.out.println(Thread.currentThread().getName() + "线程调用了该方法1");
            System.out.println(Thread.currentThread().getName() + "线程调用了该方法2");
            System.out.println(Thread.currentThread().getName() + "线程调用了该方3");
        }
    }
}

运行结果:

 

 由结果可知:两个线程执行静态方法是异步执行的

首先要明确:锁是对象而不是变量名

假如Thread-0先在运行a="444"之前,时间片划归Thread-1,然后Thread-1尝试获取a指向的"123",但发现a已经上锁了,,所以不执行,时间片再次划给Thread-0,然后0继续执行,执行完a="444"后,Thread-1需要获取的不是"123"而是"444",所以获取到了,两个线程异步执行

 

posted @ 2022-05-21 19:57  dronff  阅读(43)  评论(0)    收藏  举报