同步方法与非同步方法同时执行

Synchronized method execute with non-synchronized method at the same time

这是代码

public class Test {

  public static void main(String[] args) {

    PrintLoop pl = new PrintLoop();

    Thread a = new Thread(() -> {
      String threadName = Thread.currentThread().getName();
      pl.print(threadName, 5);
      pl.printTenTiems(threadName);
    }, "A");

    Thread b = new Thread(() -> {
      String threadName = Thread.currentThread().getName();
      pl.print(threadName, 5);
    }, "B");

    a.start();
    b.start();
  }

}

class PrintLoop{
  public synchronized void print(String threadName, int times){
    System.out.println(threadName + ":print start");
    for(int i = 0; i < times; i++){
      System.out.println(threadName + ":" + i);
    }
    System.out.println(threadName + ":print end");
  }

  public void printTenTiems(String threadName){
    System.out.println(threadName + ":printTenTiems start");
    for(int i = 0; i < 10; i++){
      System.out.println(threadName + ":" + i);
    }
    System.out.println(threadName + ":printTenTiems end");
  }

}

谁能解释为什么在线程 B 中调用的 pl.print() 没有被锁定并且与 pl.printTenTimes() 同时执行?据我所知,同步方法在线程中调用时将锁定整个对象。

当您在(非静态)方法上使用 synchronized 关键字时,调用该方法的对象将用作锁。

这与 'the whole object is locked' 不同。这意味着在执行同步方法时,另一个线程将无法将该对象用作锁。

特别是,它不会阻止另一个线程对该对象调用非同步方法。

同步方法将等待同步方法。这不适用于非同步方法

it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.