我有一个独立工作的线程池。基本上,这些线程从网站获取数据。我还有另一个线程,它改变了我的系统IP。我只需要暂停所有其他线程,而另一个线程正在更改ip。一旦ip发生变化,其他线程池就会恢复。
有什么解决方案吗?
以下是我的代码:
for(;;){
for (int aa = 0; aa < pages.size(); aa++) {
if (pageID != null) {
t = new Thread(new BackgroundThread(pageID.get(aa)));
System.out.println(pageID.get(aa));
t.start();
}
if(ipNo == 3){
ipNo = 0;
}
if(aa == 35) {
//Following method take a little bit time to change ip. I need when this method will be executin then
//all above threads "t" will be paused
IPRotator.rotateIP(ip[ipNo]);
//When IP will be change then all paused threads will be resumed
ipNo++;
}
}
}发布于 2010-07-04 05:31:54
我假设你真的想改变机器的IP地址?您需要确保线程处于可以更改系统IP的状态,并且系统IP转换器需要等待,直到所有线程都暂停以更改IP。
这可以使用CountDownLatch来指示线程应该暂停-每个线程向下计数锁存器。当所有线程都命中锁存器时,系统IP更新器可以继续。一旦它完成了它的工作,它就会通过将闩锁设置为null来恢复线程。
为清楚起见,省略了异常处理。
class SystemIPChanger implements Runnable {
Collection<WorkerThread> pool;
public void changeIP() {
pauseAllThreads();
changeIP();
resumeThreads();
}
void pauseAllThreads() {
CountDownLatch latch = new CountDownLatch(pool.size());
for (WorkerThread worker : pool) {
worker.setPause(latch);
}
latch.await();
}
void resumeThreads() {
for (WorkerThread worker : pool) {
worker.setPause(null);
}
}
}
class WorkerThread implements Runnable {
private CountDownLatch pause;
public void run() {
while (...) {
pause();
doRealWork();
}
}
synchronized void pause() {
CountdownLatch latch = pause;
if (latch!=null) {
latch.countDown();
while (pause==latch) {
wait();
}
}
}
public synchronized void setPause(CountDownLatch latch) {
this.pause = latch;
notifyAll();
}
}发布于 2010-07-04 05:10:15
使用某种读/写锁怎么样?线程作为读取器执行正常工作(以相对较小的块为单位,因此它们可以及时中断),而需要更改IP的线程作为写入器执行此操作。
发布于 2010-07-04 05:31:51
在java1.5API中尝试这个类ReadWriteLock。
https://stackoverflow.com/questions/3172874
复制相似问题