以下是一个简单的多线程爬虫实现

来源:互联网 发布:形容傻天真网络词 编辑:程序博客网 时间:2024/04/29 17:40
//以下是一个简单的多线程爬虫实现
package thread;


import java.util.concurrent.Callable;




public class MThread extends Thread{

threadList = new ArrayList<Thread>(THREAD_NUM);
for(int i = 0; i < THREAD_NUM; i++){
Thread t = new Thread(this, "Spider Thread #" + (i + 1));
t.start();
threadList.add(t);
}

//当前线程等待子线程退出
while(threadList.size() > 0){
Thread child = (Thread) threadList.remove(0);
child.join();
}

//子程序主要的执行程序如下:
public synchronized NewSource dequeueURL() throws Exception{
while(true){
if(!todo.isEmpty()){
NewsSource newitem = (NewsSource)todo.removeFirst();
visited.add(newitem.URL, newitem.source);
return newiyem;
}
else
{
//等待线程数的计数器减一
threads--;

//如果仍然有其他的线程在活动则等待
if(threads > 0){
wait();
threads++;
}
else{
notifyAll();
return null;
}


}

}
}

//enqueueURL把发现的URL放入TODO表
public synchronizesed void enqueueURL(NewSource newitem){
if(!visited.contains(newitem.URL)){
todo.add(newitem);
visited.add(newitem.URL, newitem.source);

//唤醒在等待的线程

}

}
public void run(){
NewsSource item;
try{
while((item == dequeueURL()) !=null){
//包含把新的URL放入TODO表的过程
indexURL(item);
}
}
catch(Exception e){
e.printStackTrace();
}
threads--;
 }

}
0 0
原创粉丝点击