【发布时间】: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