public class Share_class {
  private int page_count;
  private int page_id;
  //private  boolean   processing=false;  //标志以下两个synchronized方法的执行.
  boolean[]  page_array;
  public share_class(int page_count)
  {
    this.page_count = page_count;
    page_array = new boolean[page_count]; /*保存页面是否被处理的状态,因为boolean型默认为false,设false 为没被处理过.*/  }
  public synchronized int select_page ()
  {
    int n;
    for (n = 0 ; n < page_count ; n++)
    {
      if (!page_array[n] )     //找出没有被正在处理或已处理过的页
      {
         page_id = n + 1; //因为ppt处理要从1开始;
         break;
      }
    }    if (page_id <= page_count) /* if page_id < page_count, it means there are still some pages left*/
      return page_id;
    else
      return -1;//没有页面了就返回 -1;
  }  
  
  public synchronized void finish_page(int page_id)
  {
    page_array[page_id] = true ; //update 对应页面数组位置为已处理过.
  }
}
public class Page_thread  implements Runnable{  Share_class share = null;
  Object pages = null;
  HashTable h1 = null;  public Page_thread(Share_class share,Object pages,Hashtable hash)
  {
    this.share = share;
    this.pages = pages;
    this.h1 = hash;
  }
  public void run()
  {
     int page_id  = share.select_page();
     if (page_id != -1) // if there are more pages
       share.finish_page(page_id);
      
  }  public  static void main(String[] args) {
    ....
    int page_count = 50;
    Share_class test = new Share_class(page_count);
    Runnable runnable = new Page_thread(test,pages,h1);    Thread thread1 = new Thread(runnable);
    Thread thread2 = new Thread(runnable);
    thread1.start();
    thread2.start();
    ......
  }
}------------------
sorry, i can't type Chinese currently.You don't have to use 'wait()' and 'notify()',  because   select_page() and finish_page() is synchronized, so the system will guarantee only one thread can call select_page() and finish_page() at one time.If a second thread is trying to call select_page() while the first one is still calling, the system will block the second one untill the first thread finish its function and release the lock

解决方案 »

  1.   

    sorry, i must go now, the code I provide is not completely correct,  I'll provide another one later time today, probably after 7:00pm
      

  2.   

    Thanks for your help .
    i will study it clearly ,and think it over .
      

  3.   

    我上面贴的大致思路应该对的。可能有些细节会有点偏差,不过不影响多线程的操作。 
    其实只要清楚synchronized的用法就可以了。   上面只用了synchornized的一种用法,synchronized还有另一种用法。 书上都有讲的。 也欢迎交流。 若需要交流,可以给我留言