欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用Vector实现简单线程池

程序员文章站 2022-06-21 10:57:07
...
主要原理:
一、 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();
}
}
}
相关标签: thread 线程