开发者

Java Pause Execution

I have a pool of threads which are working independently. Basically these threads are getting data from websites. I have also another thread which change my System IP. I just need to pause all other threads while another thread is changing ip. As soon as ip will change then other threads pool will resume.

Is there any solution?

Here is my Code:

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 wil开发者_C百科l 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++;
    }
  }
}


I'm assuming you really mean you are changing the machine IP? You need to be sure that the threads are in a state where the system IP can be changed, and also that the system IP changer needs to wait until all threads are pausing for the IP to be changed.

This can be done using a CountDownLatch to indicate that threads should pause - each thread counts down the latch. When all threads have hit the latch, the system IP updater can proceed. Once it's done it's work, it then resumes the threads by setting the latch to null.

Exception handling omitted for clarity.

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


How about using some sort of Read/Write lock? The threads do their normal work (in relatively small chunks, so they can be interrupted in a timely fashion) as a reader, and the thread that needs to change IP does so as a writer.


Try this class ReadWriteLock in the java 1.5 api.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜