独自のスレッドプール
1743 ワード
生産者消費者が実現したJavaスレッドプールを自分でシミュレートし、jdk 5の新しいconcurrentパッケージの内容を使用していません.
ひかくきそ
ひかくきそ
import java.util.*;
public class MyThreadPool{
private LinkedList taskList ;
private ArrayList threadList;
private boolean flag = false;
private volatile boolean threadRun = true;
private int curPoint = 0;
// false true
public MyThreadPool(int size){
this.threadList = new ArrayList<>(size);
this.taskList = new LinkedList<>();
for(int i = 0; i < size; ++i){
this.threadList.add(new Thread(){
public void run(){
System.out.println("==!");
execute();
}
});
}
}
public void submitTask(Runnable runnable){
if(this.curPoint < threadList.size()){
threadList.get(curPoint).start();
System.out.println(this.threadList.get(curPoint));
this.curPoint++;
}
try{
synchronized(this.taskList){
this.taskList.addLast(runnable);
this.taskList.notifyAll();
}
}
catch(Exception ex){
//System.out.println(ex);
}
}
private void execute(){
while(true){
try{
Runnable runnable = null;
synchronized(this.taskList){
if(!this.threadRun){
this.taskList.notifyAll();
break;
}
if(this.taskList.size() == 0){
this.taskList.wait();
}
runnable = this.taskList.removeFirst();
}
runnable.run();
}catch(Exception ex){
//System.out.println(ex);
}
}
}
public void cancel(){
this.threadRun = false;
this.submitTask(new Runnable(){
public void run(){
}
});
//System.out.println(this.taskList.size());
this.taskList.clear();
}
}