线程问题:高手求救:
//选取页面未被处理的页面
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 为没被处理过.
}
synchronized int select_page ()
{
while(processing)//finish_page 正在处理,等待
{
try {
wait();
}
catch(InterruptedException e)
{
System.out.println("Exception:"+ e.toString());
}
}
int n;
for (n=0;n<page_count;n++)
{
if (!page_array[n] ) //找出没有被正在处理或已处理过的页
{
page_id = n+1; //因为ppt处理要从1开始;
break;
}
}
processing = true;
notify();
if (page_id> -1)
{
return page_id;
}
else
return -1;//没有页面了就返回 -1;
}
synchronized void finish_page(int page_id)
{
while(!processing)//select_page处理.
{
try
{
wait();
}
catch(InterruptedException e)
{
System.err.println("Exception :" + e.toString());
}
}
page_array[page_id] =true ; //update 对应页面数组位置为已处理过.
processing =false;
notify();
}
}
//处理页面的线程;
public class page_thread implements Runnable{
public page_thread(share_class share,Object pages,Hashtable hash)
{
this.share = share;
this.pages = pages;
this.h1 = hash;
}
public void run()
{
page_id = share.select_page();
share.finish_page(page_id);
if (page_id != -1) {
process page;
}}}
//主程序
....
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();
......
}
请大侠帮忙:
问题:1)share_class 我本意是进行同步处理,使线程不会处理同一页面,但是运行结果还是处理同一页面,
2) 本意是让thread1,thread2处理不同页面,两者负责将50页面全部处理完,但是两者都只处理了第一页,其他49页都没有处理,
请大侠帮忙解决同步问题和循环问题,
谢谢先.