线程池的实现 java源码_java实现的简易线程池框架源码

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++

}

}简单请求:

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值