SyncQueue:工作队列 此数据结构为循环队列
public class SyncQueue { Object arry[]; int head=0; int tale=0; int size; public SyncQueue(int size) { // TODO Auto-generated constructor stub this.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 block e.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 block e.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:处理SyncQueue队列中请求的工作线程
public class Worker implements Runnable{ private SyncQueue q; public Worker(SyncQueue queue) { q=queue; } @Override public void run() { // TODO Auto-generated method stub while(true){ Runnable task=(Runnable)q.get(); task.run(); } } }
简易线程池:
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); } }
简单请求:
public class MyTask implements Runnable{ public MyTask(int index){ this.index=index; } int index; @Override public void run() { // TODO Auto-generated method stub System.out.println(index+" work run"); } }
测试:
import org.junit.Test; public class ThreadpoolTest { @Test public 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 block e.printStackTrace(); } queue.put(new MyTask(size)); } pool.initWorker(new Worker(queue)); pool.do_work(); new Runnable() { @Override public void run() { // TODO Auto-generated method stub int size=0; while(size++<200){ try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } queue.put(new MyTask(size)); } } }.run(); System.out.println("weichao"); } }