1、线程池特性
package cn.bruce.Thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //JDK1.5新特性,实现线程池程序 public class ThreadPoolDemo { public static void main(String[] args) { // 调用工厂类方法,创建线程池对象 // 返回线程池对象,是返回的接口 ExecutorService ES = Executors.newFixedThreadPool(2); // 调用接口实现类对象es中的方法submit提交一个线程任务 ES.submit(new Runnable() { @Override public void run() { System.out.println(new Thread().currentThread().getName()+"线程任务提交");//提交后不会停止 } }); ES.submit(new Runnable() { @Override public void run() { System.out.println(new Thread().currentThread().getName()+"线程任务提交");//提交后不会停止 } }); } }
2、Callable方式进行线程任务
package cn.bruce.Thread; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; //线程实现异步计算 //两个线程,一个实现1到100求和,一个实现1到200求和 public class CallableDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService eService = Executors.newFixedThreadPool(2); Future<Integer> f1 = eService.submit(new Callabletest(100)); Future<Integer> f2 = eService.submit(new Callabletest(200)); System.out.println(f1.get()); System.out.println(f2.get()); eService.shutdown(); } } class Callabletest implements Callable<Integer> { private int a; public Callabletest(int a) { this.a = a; } public Integer call() { int sum = 0; for (int i = 0; i <= a; i++) { sum = sum + i; } return sum; } }