一,线程池
二, 如何创建线程池
案例:
//1,通过ThreadPoolExecuter创建一个线程池对象ExecutorService pool = new ThreadPoolExecutor(3,5,8,TimeUnit.SECONDS,new LinkedBlockingQueue<>(4),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
三,处理Runnable任务
超过了最大线程量后的处理方法:
四,案例
package XianChengChildren;import java.util.concurrent.*;public class ThewadPoolTest1 {public static void main(String[] args) {//1,通过ThreadPoolExecuter创建一个线程池对象ExecutorService pool = new ThreadPoolExecutor(3,5,8,TimeUnit.SECONDS,new LinkedBlockingQueue<>(4),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());//2,处理Runnable任务Runnable target =new MyRunnable();//执行任务 executepool.execute(target);pool.execute(target);pool.execute(target);pool.execute(target);pool.execute(target);pool.execute(target);//执行完后关闭线程池pool.shutdown();//立刻关闭,不管临时任务//pool.shutdownNow();}
}
package XianChengChildren;public class MyRunnable implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"===>输出666~~");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}
}
五,处理Callable任务
六,案例
package XianChengChildren;import java.util.concurrent.*;public class ThewadPoolTest1 {public static void main(String[] args) throws ExecutionException, InterruptedException {//1,通过ThreadPoolExecuter创建一个线程池对象ExecutorService pool = new ThreadPoolExecutor(3,5,8,TimeUnit.SECONDS,new LinkedBlockingQueue<>(4),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());//2,处理Callable任务Future<String> f1 = pool.submit(new MyRunnable(100));Future<String> f2 = pool.submit(new MyRunnable(200));Future<String> f3 = pool.submit(new MyRunnable(300));Future<String> f4 = pool.submit(new MyRunnable(400));System.out.println(f1.get());System.out.println(f2.get());System.out.println(f3.get());System.out.println(f4.get());}
}
package XianChengChildren;import java.util.concurrent.Callable;public class MyRunnable implements Callable {private int n;public MyRunnable(int n) {this.n = n;}@Overridepublic Object call() throws Exception {int sum=0;for (int i = 0; i <=n ; i++) {sum+=1;}return Thread.currentThread().getName()+"线程求出了1-"+n+"的和是"+sum;}
}