-
线程的实现方式
-
线程池的使用
java的线程池默认封装了五个通用的线程池:
1、Executors.newSingleThreadExecutor()
2、Executors.newFixedThreadPool(2)
3、Executors.newCachedThreadPool()
4、Executors.newScheduledThreadPool(2)
5、Executors.newWorkStealingPool()
newFixedThreadPool的是实例化如下所示:
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
和newSingleThreadExecutor唯一的区别就是核心线程池数和最大线程数可以按照需求自定义,其他的都是一致的。
示例代码:
public class FixedThreadPoolTest { // 线程数 private static final int threads = 10; // 用于计数线程是否执行完成 CountDownLatch countDownLatch = new CountDownLatch(threads); /** * newFixedThreadPool execute * * @throws ExecutionException * @throws InterruptedException */ @Test public void test1() throws ExecutionException, InterruptedException { System.out.println("---- start ----"); ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2); for (int i = 0; i < threads; i++) { fixedThreadPool.execute(() -> { try { System.out.println(Thread.currentThread().getName()); } catch (Exception e) { System.out.println(e); } finally { countDownLatch.countDown(); } }); } countDownLatch.await(); System.out.println("---- end ----"); } /** * newFixedThreadPool submit submit */ @Test public void test2() throws InterruptedException { System.out.println("---- start ----"); ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2); for (int i = 0; i < threads; i++) { // Callable 带返回值 fixedThreadPool.submit(new Thread(new Runnable() { @Override public void run() { try { System.out.println(Thread.currentThread().getName()); } catch (Exception e) { e.printStackTrace(); } finally { countDownLatch.countDown(); } } })); } countDownLatch.await(); System.out.println("---- end ----"); } /** * newFixedThreadPool submit Callable * * @throws ExecutionException * @throws InterruptedException */ @Test public void test3() throws ExecutionException, InterruptedException { System.out.println("---- start ----"); ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2); for (int i = 0; i < threads; i++) { // Runnable 带返回值 FutureTask<?> futureTask = new FutureTask<>(new Callable<String>() { /** * call * @return currentThreadName */ @Override public String call() { return Thread.currentThread().getName(); } }); fixedThreadPool.submit(new Thread(futureTask)); System.out.println(futureTask.get()); } System.out.println("---- end ----"); } }