SyncQueue: work queue. The data structure is cyclic queue.
public class SyncQueue {Object arry[];int head=0;int tale=0;int size;public SyncQueue(int size) {// TODO Auto-generated constructor stubthis.size=size;arry=new Object[size];}public synchronized void put(Object object){while(full()){try {System.out.println("is full");wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}arry[tale]=object;tale=(tale+1)%size;notify();System.out.println("put notify");}public synchronized Object get(){while(empty()){try {System.out.println("is empty");wait();System.out.println("get wait");} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}Object o=arry[head];head=(head+1)%size;notify();System.out.println("get notify");return o;}public boolean full(){return ((tale-head+size)%size)==(size-1);}public boolean empty(){return head==tale;}}
Worker: The Worker thread that processes requests in the SyncQueue queue.
public class Worker implements Runnable{private SyncQueue q;public Worker(SyncQueue queue) {q=queue;}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){Runnable task=(Runnable)q.get();task.run();}}}
Simple thread pool:
public class Threadpool {private int size;private Worker worker;public Threadpool(int size){this.size=size;}public void initWorker(Worker worker){this.worker=worker;}public void do_work(){int i=0;do{new Thread(worker).start();}while(i++<size);}}
Simple request:
public class MyTask implements Runnable{public MyTask(int index){this.index=index;}int index;@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println(index+" work run");}}
Test:
import org.junit.Test;public class ThreadpoolTest {@Testpublic void test() {final SyncQueue queue=new SyncQueue(50);Threadpool pool=new Threadpool(5);int size=0;while(size++<20){try {Thread.sleep(500);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}queue.put(new MyTask(size));}pool.initWorker(new Worker(queue));pool.do_work();new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubint size=0;while(size++<200){try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}queue.put(new MyTask(size));}}}.run();System.out.println("weichao");}}