java简单线程池实例代码


package aa;

import java.util.Random;

public class DownThread extends Thread {

private boolean runFlag;

public boolean isRunFlag() {

return runFlag;

}

public DownThread(){

System.out.println(this.getName()+" 初始化");

this.setRunFlag(false);

}

public synchronized void setRunFlag(boolean runFlag) {

this.runFlag=runFlag;

if(runFlag)this.notify();

}

public synchronized void run(){

while (true){

if(!this.isRunFlag()){

try{

this.wait();

}catch(InterruptedException e){

e.printStackTrace();

}

}

System.out.println(this.getName()+"doingsomething!");

Random ran=new Random();

try{

long l=10001*(ran.nextInt(10)+1);

System.out.println("这活要干 "+l+"毫秒");

sleep(l);

}catch(InterruptedException e){

e.printStackTrace();

}

System.out.println(this.getName()+"done!");

this.setRunFlag(false);

System.out.println(this.getName()+"回收");

ThreadPool.removeThread(this);

}

}

}


============================================================================

package aa;

import java.util.LinkedList;

public class ThreadPool {

final static int MaxLength=20;

private static LinkedList pool=null;

public ThreadPool(){

System.out.println("初始化线程池="+MaxLength);

pool=new LinkedList();

for(int i=0;i<MaxLength;i++){

DownThread thread=new DownThread();

removeThread(thread);

thread.start();

}

}

public boolean isFull(){

return pool.isEmpty();

}

public void addThread(){

synchronized (pool) {

while(this.isFull()){

System.out.println("线程池满,等待中。。。。。");

try{

pool.wait();

}catch(InterruptedException e){

e.printStackTrace();

}

}

DownThread thread=(DownThread)pool.removeFirst();

if(!thread.isRunFlag()){

System.out.println(thread.getName()+"is processing");

thread.setRunFlag(true);

}

}

}

public static void removeThread(DownThread downThread) {

synchronized (pool) {

pool.addLast(downThread);

pool.notify();

}

}

public static void main(String[] args){

ThreadPool test=new ThreadPool();

for(int i=0;i<1000;i++){

test.addThread();

}

}

}

package aa;

public class TestThread extends Thread{

public static void main(String args[]){

Runner r=new Runner();

Thread t1=new Thread(r);

Thread t2=new Thread(r);

t1.start();

t2.start();

}

}

class Runner implements Runnable{

public Runner(){

super();

}

public void run(){

for(int i=0;i<20;i++){

System.out.println("NO."+i);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值