线程池是Java中一种重要的多线程结构,可以有效控制线程的并发数量和复用,避免频繁创建和销毁线程造成系统资源浪费。
如何得到线程对象
1.使用ExecutorService的实现类ThreadPoolExecutor自创建一个线程池对象
// 处理Runnable任务 public class MyThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName()+"输出666~"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }
public class Test { public static void main(String[] args) { ExecutorService pool = new ThreadPoolExecutor(3,5,8, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); Thread target = new MyThread(); pool.execute(target); pool.execute(target); pool.execute(target); pool.execute(target); pool.execute(target); pool.execute(target); pool.execute(target); pool.execute(target); pool.execute(target); pool.execute(target);//拒绝执行该线程 } }
// 处理Callable任务 package XianchengChi; import java.util.concurrent.Callable; public class CallableAndFuturetask implements Callable<String>{ private int n; public CallableAndFuturetask(int n){ this.n =n; } @Override public String call() throws Exception{ int sum = 0; for(int i =1;i<=n;i++){ sum+=i; } return Thread.currentThread().getName()+"求出的和是"+sum; } }
public class Test { public static void main(String[] args) throws Exception{ ExecutorService pool = new ThreadPoolExecutor(3,5,8, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy()); Future<String> f1 = pool.submit(new CallableAndFuturetask(100)); Future<String> f2 = pool.submit(new CallableAndFuturetask(200)); Future<String> f3 = pool.submit(new CallableAndFuturetask(300)); Future<String> f4 = pool.submit(new CallableAndFuturetask(400)); System.out.println(f1.get()); System.out.println(f2.get()); System.out.println(f3.get()); System.out.println(f4.get()); } }
新任务拒绝策略
2.使用Executors(线池的工具类)调用方法返不同特点的线程池对象
public class CallableAndFuturetask implements Callable<String>{ private int n; public CallableAndFuturetask(int n){ this.n =n; } @Override public String call() throws Exception{ int sum = 0; for(int i =1;i<=n;i++){ sum+=i; } return Thread.currentThread().getName()+"求出的和是"+sum; } }
public class Test { public static void main(String[] args) throws Exception{ ExecutorService pool = Executors.newFixedThreadPool(3); Future<String> f1 = pool.submit(new CallableAndFuturetask(100)); Future<String> f2 = pool.submit(new CallableAndFuturetask(200)); Future<String> f3 = pool.submit(new CallableAndFuturetask(300)); Future<String> f4 = pool.submit(new CallableAndFuturetask(400)); System.out.println(f1.get()); System.out.println(f2.get()); System.out.println(f3.get()); System.out.println(f4.get()); } }
不推荐使用Executors创建线程池。尽量通过ThreadPoolExecutor的方式创建,这样可规避资源耗尽的风险