线程池的线程复用,个人理解

一个线程一般在执行完任务后就结束了,怎么再让他执行下一个任务呢

其实,原理是:

   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();//生产任务


}

}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值