Assuming a class has two methods like the ones below:
public synchronized void methodA() {
// do some stuff
new Thread() {
public void run() {
methodB();
}
}.start();
}
public synchronized void methodB() {
// do some stuff
}
and we call methodA()
, will the new thread be blocked by the one that called methodA()
?
Probably not: new Thread().start()
returns immediately, so by the time the new thread actually gets started and methodB()
is called, it is very likely that the original thread will have already exited methodA()
.
If however you do:
public synchronized void methodA() throws InterruptedException {
new Thread() {
public void run() {
methodB();
}
}.start();
Thread.sleep(10000);
}
your methodB
will block for approximately 10 seconds, waiting for the original thread to release the lock.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.