常梦网 常梦网

Java执行器入门

时间: 2024-07-04  热度:

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);    }    /**

}

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;    }@Overridepublic void run() {try {        System.out.println(this.name+"----开始执行任务");        Thread.sleep((long) (Math.random()*1000));        System.out.println(this.name+"----结束执行任务");    } catch (InterruptedException e) {    e.printStackTrace();    }    }

}

相关阅读