使用Vector实现简单线程池

主要原理:
一、 ThreadPoolManager在实例化时创建十个线程,放入Vector中。
二、 每个SimpleThread线程的是否在运行的标记runningFlag设置为false。
三、 当使用ThreadPoolManager的process方法处理时,遍历Vector中的线程,如果当前遍历到的线程不在运行中,则使用当前线程,并设置运行标记runningFlag为true。
四、 当前线程的运行标记位为false时,线程wait(),为true时开始处理字符串。
五、 为了使得线程运行时每个线程独占一个任务,在SimpleThread的run()方法中使线程sleep(5000),这样一个线程接手一个任务后,在睡眠期间再来其他任务由下个标记为false的线程接手。
代码如下:

// SimpleThread:
public class SimpleThread extends Thread {

private boolean runningFlag;
private String argument;

public boolean isRunning() {
return runningFlag;
}

public synchronized void setRunning(boolean flag) {

runningFlag = flag;
if (flag) {
this.notify();
}
}

public String getArgument() {

return argument;
}

public void setArgument(String string) {

argument = string;
}

public SimpleThread(int threadNumber) {
runningFlag = false;
System.out.println("thread " + threadNumber + " started;");
}

public synchronized void run() {
try {
while (true) {
if (!runningFlag) {
this.wait();
} else {
System.out.println("processing: " + getArgument() + "..done");
sleep(5000);
System.out.println("thread is sleeping");
setRunning(false);
}
}
} catch (InterruptedException e) {
System.out.println("InterruptedException");
}

}
}

//ThreadPoolManager:

public class ThreadPoolManager {

private int maxThread;

public Vector vector;

public void setMaxThread(int threadCount) {
maxThread = threadCount;

}

public ThreadPoolManager(int threadCount) {
setMaxThread(threadCount);
System.out.println("starting thread pool....");

vector = new Vector();
for (int i = 0; i < 10; i++) {
SimpleThread thread = new SimpleThread(i);
vector.addElement(thread);
thread.start();
}
}

public void process(String argument) {

int i;
for (i = 0; i < vector.size(); i++) {
SimpleThread currentThread = (SimpleThread) vector.elementAt(i);
if (!currentThread.isRunning()) {
System.out.println("thread" + (i + 1) + "is processing::"
+ argument);
currentThread.setArgument(argument);
currentThread.setRunning(true);
break;
}
if (i == (vector.size() - 1)) {

System.out.println("pool is full,try in another time.");
}

}
}
}

//测试类
public class TestThreadPool {

public static void main(String[] args) {
try {

BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String s;
ThreadPoolManager manager = new ThreadPoolManager(10);
while ((s = br.readLine()) != null) {
manager.process(s);
}

} catch (IOException e) {
e.printStackTrace();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值