-
How the thread is implemented
-
Use of thread pool
Java's thread pool encapsulates five general thread pools by default:
1、Executors.newSingleThreadExecutor()
2、Executors.newFixedThreadPool(2)
3、Executors.newCachedThreadPool()
4、Executors.newScheduledThreadPool(2)
5、Executors.newWorkStealingPool()
The newFixedThreadPool is instantiated as follows:
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
The only difference from newSingleThreadExecutor is that the number of core thread pools and the maximum number of threads can be customized according to requirements, and the others are the same.
Sample code:
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 ----"); } }