java實現的簡易線程池架構源碼

來源:互聯網
上載者:User

SyncQueue:工作隊列 此資料結構為迴圈隊列

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:處理SyncQueue隊列中請求的背景工作執行緒

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();}}}

簡易線程池:

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;@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println(index+" work run");}}

測試:

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");}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.