Executors建立四種線程池

newCachedThreadPool建立一個可緩存線程池,若是線程池長度超過處理須要,可靈活回收空閒線程,若無可回收,則新建線程。
newFixedThreadPool 建立一個定長線程池,可控制線程最大併發數,超出的線程會在隊列中等待。
newScheduledThreadPool 建立一個定長線程池,支持定時及週期性任務執行。
newSingleThreadExecutor 建立一個單線程化的線程池執行任務。java

 

 
package com.xhx.java;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

// Executors四種線程池
public class AppTest
{
private Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
//Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " run");
} catch (Exception e) {
e.printStackTrace();
}
}
};

private Runnable myRunnableSleep = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + " run");
} catch (Exception e) {
e.printStackTrace();
}
}
};


/**
* newCachedThreadPool:建立可緩存的線程池,若是線程池中的線程在60秒未被使用就將被移除,在執行新的任務時,
* 當線程池中有以前建立的可用線程就重用可用線程,不然就新建一條線程
* public static ExecutorService newCachedThreadPool() {
* return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
* 60L, TimeUnit.SECONDS,
* new SynchronousQueue<Runnable>());
* }
*/
@Test
public void testCachedThreadPool() throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();//線程池裏面的線程數會動態的變化,並可在線程被重用前重用
for(int i = 0; i<=20;i++){
executorService.execute(myRunnable);
}

Thread.sleep(100000);
}
/*
運行結果:出現可重用線程
pool-1-thread-2 run
pool-1-thread-1 run
pool-1-thread-3 run
pool-1-thread-3 run
pool-1-thread-2 run
pool-1-thread-4 run
pool-1-thread-3 run
pool-1-thread-1 run
pool-1-thread-2 run
pool-1-thread-4 run
pool-1-thread-3 run
pool-1-thread-2 run
pool-1-thread-1 run
pool-1-thread-5 run
pool-1-thread-4 run
pool-1-thread-6 run
pool-1-thread-7 run
pool-1-thread-8 run
pool-1-thread-9 run
pool-1-thread-10 run
pool-1-thread-11 run
*/


/**
* newScheduledThreadPool:建立一個可延遲執行或按期執行的線程池
*/
@Test
public void testScheduledThreadPool() throws InterruptedException {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
//5s第一次執行,以後3秒執行一次
executorService.scheduleAtFixedRate(myRunnable,5,3,TimeUnit.SECONDS);

Thread.sleep(20000);
}

/**
* newSingleThreadExecutor:建立一個單線程的Executor,若是該線程由於異常而結束就新建一條線程來繼續執行後續的任務
*/
@Test
public void testSingleThreadExecutor() throws InterruptedException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
for(int i = 0; i<=20;i++){
executorService.execute(myRunnable);
}
Thread.sleep(20000);
}

/**
* 建立可重用且固定線程數的線程池,若是線程池中的全部線程都處於活動狀態,
* 此時再提交任務就在隊列中等待,直到有可用線程;若是線程池中的某個線程因爲異常而結束時,線程池就會再補充一條新線程。
*/
@Test
public void testFixedThreadPool() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
for(int i = 0; i<=20;i++){
executorService.execute(myRunnableSleep);
}
Thread.sleep(200000);
}
}

緩存

相關文章
相關標籤/搜索