public class ThreadPool {
private List<Thread> listThread = new ArrayList<Thread>();
private List<Task> listRunnable = new ArrayList();
private int size;
public ThreadPool(int size){
this.size = size;
for(int i = 0; i < size; i++){
MyThread th = new MyThread(listRunnable, i+1);
th.start();
}
}
public void excuteRun(Task runnable){
synchronized(listRunnable){
listRunnable.add(runnable);
listRunnable.notifyAll();
}
}
}
class MyThread extends Thread{
private List<Task> listRunnable;
private int i;
public MyThread(List<Task> listRunnable,int i){
this.listRunnable = listRunnable;
this.i = i;
}
public void run(){
while(true){
Task runnable = null;
synchronized (this.listRunnable) {
if(this.listRunnable.size() > 0){
runnable = this.listRunnable.remove(0);
}else{
try {
this.listRunnable.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if(runnable != null){
runnable.setJ(i);
runnable.run();
}
}
}
}
class Task implements Runnable{
private int k ;
private int j;
public Task(int i){
k = i;
}
@Override
public void run() {
System.out.println("第" + this.getJ() +"个线程,执行的" + k +"个任务");
}
public int getJ() {
return j;
}
public void setJ(int j) {
this.j = j;
}
}