62,623
社区成员
发帖
与我相关
我的任务
分享
public void run() {
while (isrun) {
for (int i = 0; i < crawledUrls.size(); i++) {
//while (isrun) {
try {
if (pause) {
synchronized (this) {
wait();
}
}
do sth
//thread sleep every 0.2 sencond, max number of link crawled within one second will be 5
Thread.sleep(200);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("----thread interrupted----");
}
}
}
}
package 线程;
public class Threadtest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
CircularBuffer cb=new CircularBuffer(20);
//因为要调用的两个方法put和get是排斥,所以调用时由同一个对象调用,所以
//都是cb,注意注意!!!!!!
Producer pro=new Producer(cb);
Consumer con=new Consumer(cb);
//
Thread a=null;
Thread b=null;
a=new Thread(pro);
b=new Thread(con);
b.start();
a.start();
}
}
import java.io.*;
public class CircularBuffer {
int bufsize;
int[] store;
int numOfEntries=0;
int front=0;
int back=0;
CircularBuffer(int n)
{
bufsize=n;
store=new int[bufsize];
}
synchronized void put(int obj)throws Exception{
if(numOfEntries==bufsize)
{
System.out.println("Producer waiting");
wait();
}
store[back]=obj;
back++;
if(back==bufsize) back=0;
else {numOfEntries++;
System.out.println("putting "+ obj);
notify();
}
}
synchronized int get() throws Exception{
int result=0;
if(numOfEntries==0)
{
System.out.println("Consumer waiting");
wait();
}
else{
result=store[front];
front++;
if(front==bufsize) front=0;
numOfEntries--;
System.out.println("getting "+result);//;
notify();
}
return result;
}
}
public class Producer implements Runnable {
CircularBuffer cbp=null;
Producer(CircularBuffer cb)
{
cbp=cb;
}
public void run(){
for(int i=0;i<=50000;i++)
try{
cbp.put(i);
}
catch (Exception err){
//System.
}
}
}
public class Consumer implements Runnable {
CircularBuffer cbc=null;
Consumer(CircularBuffer cb)
{cbc=cb;}
public void run(){
for(int i=0;i<=50000;i++)
try{
cbc.get();
}
catch (Exception err){
}
}
}