我看到很多使用'synchronized'實現'run'的IdleConnectionMonitorThread的例子。在我看來,這是沒有意義的。 在爲什麼IdleConnectionMonitorThread需要同步
edu.uci.ics的實施 crawler4j 4.2
public class IdleConnectionMonitorThread extends Thread {
private final PoolingHttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(PoolingHttpClientConnectionManager connMgr) {
super("Connection Manager");
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ignored) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
log.warn("newPosition: shutdown idleMonitorThread");
}
}
因爲在大多數情況下,我們只有一個IdleConnectionMonitorThread並以這種方式,同步使用它(這)沒有任何意義。
IdleConnectionMonitorThread idleConnectionMonitorThread = new IdleConnectionMonitorThread(poolingHttpClientConnectionManager)
我不知道使用 '同步' 的好處,可以使用這種方式實現的run(刪除同步)
@Override
public void run() {
try {
while (!shutdown) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
} catch (InterruptedException ignored) {
// terminate
}
}
你的意思是爲什麼等待而不是睡覺? –
不,只有一個線程,我的意思是沒有必要使用同步。 –