我有简单的代码:
public class testing {
private static Object objToSync = new Object();
public static void main(String[] args) {
String obj1 = null;
synchronized(objToSync){
System.out.println("something one");
doSomething();
System.out.println("something three ");
}
doSomething();
}
private static void doSomething() {
synchronized(objToSync){
System.out.println("something two");
}
}
Run Code Online (Sandbox Code Playgroud)
我已经阅读了几件事,但仍然对这个问题感到困惑.为什么主要的doSomething被调用?是不是要等到同步对象解锁?对不起,如果我听起来很愚蠢,我只是感到困惑.
T.J*_*der 11
是不是要等到同步对象解锁?
该锁由持有线程,这样的事实,你(在第一次调用的情况下两次同步就可以doSomething在main)没有关系,这是在同一个线程.如果另一个线程试图进入一个synchronized块objToSync,那么另一个线程将等到该线程释放所有锁.
您的代码将执行此操作:
mainobjToSync对象上当前线程的锁定doSomethingobjToSyncobjToSyncdoSomethingobjToSyncdoSomethingobjToSyncdoSomethingmain这是一个使用两个线程的示例:
public class SyncExample {
private static Object objToSync = new Object();
public static final void main(String[] args) {
Thread second;
System.out.println("Main thread acquiring lock");
synchronized (objToSync) {
System.out.println("Main thread has lock, spawning second thread");
second = new Thread(new MyRunnable());
second.start();
System.out.println("Main thread has started second thread, sleeping a moment");
try {
Thread.currentThread().sleep(250);
}
catch (Exception e) {
}
System.out.println("Main thread releasing lock");
}
System.out.println("Main thread sleeping again");
try {
Thread.currentThread().sleep(250);
}
catch (Exception e) {
}
System.out.println("Main thread waiting for second thread to complete");
try {
second.join();
}
catch (Exception e) {
}
System.out.println("Main thread exiting");
}
static class MyRunnable implements Runnable {
public void run() {
System.out.println("Second thread running, acquiring lock");
synchronized (objToSync) {
System.out.println("Second thread has lock, sleeping a moment");
try {
Thread.currentThread().sleep(250);
}
catch (Exception e) {
}
System.out.println("Second thread releasing lock");
}
System.out.println("Second thread is done");
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Main thread acquiring lock Main thread has lock, spawning second thread Main thread has started second thread, sleeping a moment Second thread running, acquiring lock Main thread releasing lock Main thread sleeping again Second thread has lock, sleeping a moment Main thread waiting for second thread to complete Second thread releasing lock Second thread is done Main thread exiting
锁是reentrant这样,如果某个线程posses锁定它可以进入基于该锁的其它synchronized块.在你的情况下,你只有一个线程(主),他正在做这样的事情
synchronized(objToSync){
System.out.println("something one");
synchronized(objToSync){
System.out.println("something two");
}
System.out.println("something three");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7216 次 |
| 最近记录: |