现在的位置: 首页 > 综合 > 正文

SpiderDone类的实现

2013年11月25日 ⁄ 综合 ⁄ 共 2010字 ⁄ 字号 评论关闭

 首先说明一下SpiderDone类的目的:

由于编写大型的Spider程序需要很多并发的线程,所以要知道Spider何时完成还是比较难的。而SpiderDone类正好可以实现这个功能。

最重要的两个方法:

synchronized public void workerBegin();//每执行一次,线程数量加一

synchronized public void workerEnd();//每执行一个,线程数量减一;

具体代码如下:

  1. package com.heaton.bot;
  2. /**
  3.  * This is a very simple object that
  4.  * allows the spider to determine when
  5.  * it is done. This object implements(实现)
  6.  * a simple lock(锁) that the spider class
  7.  * can wait on to determine completion.
  8.  * Done is defined as the spider having
  9.  * no more work to complete.
  10.  */
  11. class SpiderDone {
  12.   /**
  13.    * The number of SpiderWorker object
  14.    * threads that are currently working
  15.    * on something.
  16.    */
  17.   private int activeThreads = 0;
  18.   /**
  19.    * This boolean keeps track of if
  20.    * the very first thread(特指第一个线程) has started
  21.    * or not. This prevents this object
  22.    * from falsely reporting that the spider
  23.    * is done, just because the first thread
  24.    * has not yet started.
  25.    */
  26.   private boolean started = false;
  27.   
  28.   /**
  29.    * This method can be called to block(阻止,阻碍)
  30.    * the current thread until the spider
  31.    * is done.
  32.    */
  33.   synchronized public void waitDone()
  34.   {
  35.     try {
  36.       while ( activeThreads>0 ) {
  37.         wait();
  38.       }
  39.     } catch ( InterruptedException e ) {
  40.     }
  41.   }
  42.   /**
  43.    * Called to wait for the first thread to
  44.    * start. Once this method returns the
  45.    * spidering process has begun.
  46.    */
  47.   synchronized public void waitBegin()
  48.   {
  49.     try {
  50.       while ( !started ) {
  51.         wait();
  52.       }
  53.     } catch ( InterruptedException e ) {
  54.     }
  55.   }
  56.   /**
  57.    * Called by a SpiderWorker object
  58.    * to indicate that it has begun
  59.    * working on a workload.
  60.    */
  61.   synchronized public void workerBegin()
  62.   {
  63.     activeThreads++;
  64.     started = true;
  65.     notify();
  66.   }
  67.   /**
  68.    * Called by a SpiderWorker object to
  69.    * indicate that it has completed a
  70.    * workload.
  71.    */
  72.   synchronized public void workerEnd()
  73.   {
  74.     activeThreads--;
  75.     notify();
  76.   }
  77.   /**
  78.    * Called to reset this object to
  79.    * its initial state.
  80.    */
  81.   synchronized public void reset()
  82.   {
  83.     activeThreads = 0;
  84.   }
  85. }

同样,其他的方法不是很常用。用到的话,再回来看吧!

That’s OK!

抱歉!评论已关闭.