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

时间:2017-10-12 09:39:48

标签: java multithreading concurrency synchronized

Here is the code

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");
  }

}

Can anyone explain why the pl.print() invoked in thread B isn't locked and is executing with pl.printTenTimes() simultaneously? As I know the synchronized method will lock the whole object when invoked in a thread.

2 个答案:

答案 0 :(得分:0)

When you use the synchronized keyword on a (non-static) method, the object on which you're calling the method is used as the lock.

This isn't the same as 'the whole object is locked'. What it means is that another thread will not be able to use that object as a lock while the synchronized method is executing.

In particular, it won't prevent another thread calling unsynchronized method on that object.

答案 1 :(得分:0)

the synchronized method will wait the synchronized method. This does not apply for non-synchronized method

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.