Java 线程池

线程池(用完的线程归还到线程池中 省去创建删除 线程 操作)

public class Xianchengchi {

public static void main(String[] args) throws InterruptedException,ExecutionException {

//线程池对象=线程池工厂创建两个线程的线程池

ExecutorService es=Executors.newFixedThreadPool(2);//两个线程

MyRunnable mr=new MyRunnable(); //任务对象

//MyCallable c = new MyCallable();

CallSum cs = new CallSum(100); //任务 有参构造

//Thread t = new Thread(mr); //创建线程对象 执行此任务

es.submit(mr); //从线程池随机一个  执行此任务(c)

es.submit(mr); //随机一个线程  执行此任务    (c)

Future<String> str=es.submit(c);//执行任务调用call 方法<Integer>

String s=str.get();//Future对象获取返回值  抛异常

es.shutdown(); //销毁线程池(可以不销毁)

}

}

//任务类 实现 Runnable 接口  //父类run()方法没抛异常 子类不能抛

public class MyRunnable implements Runnable {

public void run() {

Thread.sleep(2000); //try...catch

for(int i=0;i<100;i++){ System.out.println(i); }

System.out.println(Thread.currentThread().getName());

}

}

//任务类 实现 Callable 接口  //能抛异常  有返回值

public class MyCallable implements Callable {

public Object call() throws Exception { //String

Thread.sleep(2000);

System.out.println(+Thread.currentThread().getName());

return null; //return "abc";

}

}

//任务类 实现 CallSum 接口  //有参构造

public class CallSum implements Callable<Integer>{

private int num;

public CallSum(){}

public CallSum(int num){this.num=num;}

public Integer call() throws Exception {

int sum=0;

for(int i=1;i<=num;i++){ sum+=i; }

return sum;

}

}

原文地址:https://www.cnblogs.com/javscr/p/10250915.html