不要使用synchronized(thread)
,不要这样做,不要使用synchronized(thread)
.. 重复:不要使用synchronized(thread)
:)
如果你需要等待线程'b'完成,请使用b.join(),现在你的代码可以自由地挂起在b.wait()中。
--
希望下面的源代码能给你提供一些见解,而在使用同步(线程)/通知(notify())时我认为是不好的实践。(剪切-剪切)
祝愉快
在继续之前,请确保您已经接受了Oracle的许可协议,可以在以下链接中找到:
https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewLicense-Start?LicenseUUID=7HeJ_hCwhb4AAAEtmC8ADqmR&ProductUUID=pGqJ_hCwj_AAAAEtB8oADqmS&cnum=&evsref=&sln=
Java源代码(包括在内)在init()中被调用,自Java 1.5以来,任何Java构造函数都可以有效地调用它。
private static **synchronized int** nextThreadNum() {
return threadInitNumber++;
}
//join (该方法仅使用纳秒增加毫秒,如果纳秒>500000,则毫秒为0且纳秒>0
public final **synchronized** void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
public **synchronized** void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
//stop1 在 stop 之后被调用以确保适当的权限
private final **synchronized** void stop1(Throwable th) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
checkAccess();
if ((this != Thread.currentThread()) ||
(!(th instanceof ThreadDeath))) {
security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
}
}
if (threadStatus != 0) {
resume();
stop0(th);
} else {
if (th == null) {
throw new NullPointerException();
}
stopBeforeStart = true;
throwableFromStop = th;
}
}