java 通用 线程池_Java实现通用线程池

//ThreadPoolTest.java

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;

import polarman.threadpool.ThreadPool; import polarman.threadpool.ThreadTask;

public class ThreadPoolTest ...{

public static void main(String[] args) ...{ System.out.println(""quit" 退出"); System.out.println(""task A 10" 启动任务A,时长为10秒"); System.out.println(""size 2" 设置当前线程池大小为2"); System.out.println(""max 3" 设置线程池最大线程数为3"); System.out.println();

final ThreadPool pool = new ThreadPool(3, 2); pool.init();

Thread cmdThread = new Thread()...{ public void run()...{

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

while(true)...{ try ...{ String line = reader.readLine(); String words[] = line.split(" "); if(words[0].equalsIgnoreCase("quit"))...{ System.exit(0); }else if(words[0].equalsIgnoreCase("size") && words.length >= 2)...{ try...{ int size = Integer.parseInt(words[1]); pool.setPoolSize(size); }catch(Exception e)...{

}

}else if(words[0].equalsIgnoreCase("max") && words.length >= 2)...{ try...{ int max = Integer.parseInt(words[1]); pool.setMaxPoolSize(max); }catch(Exception e)...{

}

}else if(words[0].equalsIgnoreCase("task") && words.length >= 3)...{ try...{ int timelen = Integer.parseInt(words[2]); SimpleTask task = new SimpleTask(words[1], timelen * 1000); pool.processTask(task); }catch(Exception e)...{

}

}

} catch (IOException e) ...{ e.printStackTrace();

}

}

}

};

cmdThread.start();

/**//*

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

SimpleTask task = new SimpleTask("Task" + i, (i+10)*1000); pool.processTask(task);

}*/

}

}

class SimpleTask implements ThreadTask...{

private String taskName;

private int timeLen;

public SimpleTask(String taskName, int timeLen)...{ this.taskName = taskName; this.timeLen = timeLen;

}

public void run() ...{ System.out.println(Thread.currentThread().getId() +

": START TASK "" + taskName + """);

try ...{ Thread.sleep(timeLen); } catch (InterruptedException e) ...{

}

System.out.println(Thread.currentThread().getId() +

": END TASK "" + taskName + """);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值