2010-07-03 138 views
2

我有一个独立工作的线程池。基本上这些线程正在从网站获取数据。我还有另一个线程来改变我的系统IP。我只需要暂停所有其他线程,而另一个线程正在更改ip。一旦ip变化,其他线程池将恢复。Java暂停执行

有没有解决方法?

这里是我的代码:

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++; 
    } 
    } 
} 
+3

我觉得你在这里做什么违法的事:) 反正 - 做的线程有'而(真)'在其中?显示一些代码。 – Bozho 2010-07-03 21:13:59

+0

认为积极正面! 我正在改变我的网卡IP不是非法的东西! ;-) – Novice 2010-07-03 21:25:44

+0

请使用标记代码。 – MAK 2010-07-03 21:48:13

回答

2

我假设你真的是指你正在改变机器IP?您需要确保线程处于可以更改系统IP的状态,并且系统IP更换器需要等到所有线程都暂停以便更改IP。

这可以通过使用CountDownLatch来完成,以指示线程应该暂停 - 每个线程都会计数锁存器。当所有线程都已经锁定时,系统IP更新程序可以继续。一旦完成,它就会工作,然后通过将锁定设置为空来恢复线程。

为清楚起见省略了异常处理。

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(); 
    } 
    } 
2

如何使用某种形式的读/写锁的?作为读者,线程完成他们的正常工作(相对较小的块,因此可以及时中断),而需要更改IP的线程就像作者一样。

+0

谢谢你的回答。我编辑了我的问题。请看它并建议我如何实现读写锁 – Novice 2010-07-03 21:30:46

+0

正如@rmarimon所示,Java自己的ReadWriteLock的实现(如ReentrantReadWriteLock:http://java.sun.com/j2se/1.5.0/docs/api /java/util/concurrent/locks/ReentrantReadWriteLock.html)是显而易见的答案,可能是您的最佳选择。 虽然可能有更多专业版本的其他库,但是,如果您发现需要其他内容。 – pdbartlett 2010-07-04 09:26:41