1

package com.ex;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class Server {





private   ThreadPoolExecutor  executor;



public  ThreadPoolExecutor getExecutor(){
    return  this.executor;
}


public  Server(){
    

// executor=(ThreadPoolExecutor) Executors.newCachedThreadPool();// cache线程池在真正有任务的时候才初始化,随着任务变化而变化

    executor=(ThreadPoolExecutor) Executors.newFixedThreadPool(10);//固定任务的线程池
    System.out.println("总共线程池------------------------"+executor.getPoolSize());
    System.out.println("活动的线程池数量---------------------"+executor.getActiveCount());
}

public  void  excuteTask(Task  task){
        
      executor.execute(task);
      System.out.println("一共得线程池"+executor.getPoolSize());
        System.out.println("活动的线程池数量,即正在处理任务的线程数量"+executor.getActiveCount());
}

public static void main(String[] args) {
    Server  server=new Server();
    for(int i=0;i<100;i++){
        
        Task  task=new Task("线程id"+i);
        
        server.excuteTask(task);
    }
    /**
  • 主线程不断询问线程组是否执行完毕
    */

        while(true){
    

    if(server.getExecutor().getCompletedTaskCount()==100){

       System.out.println("总共线程池------------------------"+server.getExecutor().getPoolSize());
       System.out.println("活动的线程池数量---------------------"+server.getExecutor().getActiveCount());
       server.getExecutor().shutdown();
       break;

    }

        }
        
    }
    

}

package com.ex;

import java.util.Date;

public class Task implements Runnable{


private  String  name;
private  Date  date;

public  Task(String name){
    
    this.date=new Date();
    
    this.name=name;
    
    
    
    
}


@Override
public void run() {

    
    
    try {
        System.out.println(this.name+"----开始执行任务");
        Thread.sleep((long) (Math.random()*1000));
        System.out.println(this.name+"----结束执行任务");
    } catch (InterruptedException e) {
        
        e.printStackTrace();
    }
    
}

}


happyfish
2.4k 声望66 粉丝

[链接]