线程池的线程复用,个人理解
一个线程一般在执行完任务后就结束了,怎么再让他执行下一个任务呢
其实,原理是:
run( ){
while(true){
if(没有任务){wait( );}
否则 从任务队列取出任务,执行//这样执行完任务后,又回到头,问有没有任务,没任务就等待,直至有任务
}
}
下面的代码。我生产了两个 线程作为工人
生产了10个同样的任务,让他们执行
利用复用让 2个线程完成10个任务
import java.util.ArrayList;import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
public class mythreadpool {
LinkedList<task> tasklist=new LinkedList<task>();
class task {//任务类
int id;
task(int id){
this.id=id;
System.out.println("第"+id+"个任务产生");
}
public void run() {//具体的工作
System.out.println("第"+id+"个任务正在执行");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第"+id+"个任务执行完毕");
}
}
class woker extends Thread{//工人实体
String name;
woker(String name){
this.name=name;
}
public void run() {
while(true) {
if(tasklist.size()==0){
try {
synchronized(tasklist) {
System.out.println(name+"没有任务");
tasklist.wait();//没得到任务,进入tasklist的等待队列
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized(tasklist){
System.out.println(name+"得到任务");
tasklist.removeFirst().run();
}
}
}
}
void pool(){//工人。只生产了两个工人
ArrayList<woker> wokerlist=new ArrayList<woker>();
for(int i=0;i<2;i++) {
woker k=new woker("第"+(i+1)+"个工人");k.start();
wokerlist.add(k);//
}
}
class factory extends Thread{//生产任务的线程,总共会生产10个任务
public void run() {
for(int i=0;i<10;i++) {
synchronized(tasklist) {
tasklist.addLast(new task(i+1));tasklist.notify();
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
mythreadpool k=new mythreadpool();
k.pool();//生产工人
mythreadpool.factory m=k.new factory();
m.start();//生产任务
}
}