【问题标题】:Synchronized method execute with non-synchronized method at the same time同步方法与非同步方法同时执行
【发布时间】:2017-10-12 09:39:48
【问题描述】:

这里是代码

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() 一起执行?据我所知,同步方法在线程中调用时会锁定整个对象。

【问题讨论】:

  • 因为没有理由不这样做。也许您错过了 printTenTiems 方法中的同步键盘?
  • 我是故意把synchronized关键字取出来的,我知道把它加到printTenTimes()中时,它会一次执行一个方法。
  • 由于printTenTiems 没有同步,所以它的调度没有条件,即使某些东西正在使用同一个对象进行同步。
  • 你知道错了。查一下。

标签: java multithreading concurrency synchronized


【解决方案1】:

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

这与“整个对象被锁定”不同。这意味着在执行同步方法时,另一个线程将无法将该对象用作锁。

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

【讨论】:

    【解决方案2】:

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

    在同步方法上的两次调用是不可能的 交错的相同对象。当一个线程正在执行同步 对象的方法,所有其他调用 的线程同步 相同对象块的方法(暂停执行)直到第一个 线程完成了对象。

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 2012-03-20
      • 1970-01-01
      • 2017-10-23
      相关资源
      最近更新 更多