基础的线程池
线程池主要有4类,如下
package com.ydh.test.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @description:
* @author: yangdehong
* @version: 2018/1/19.
*/
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
// new ThreadPoolExecutorTest().testCachePool();
// new ThreadPoolExecutorTest().testFixedPool();
// new ThreadPoolExecutorTest().testScheduledPool();
new ThreadPoolExecutorTest().testSinglePool();
}
/**
* 创建一个定长线程池,支持定时及周期性任务执行。
*/
private void testSinglePool() {
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
singleThreadExecutor.execute(() -> {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
/**
* 创建一个定长线程池,支持定时及周期性任务执行。
*/
private void testScheduledPool() {
// 定时执行
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(() ->
System.out.println("delay 3 seconds"),
3, TimeUnit.SECONDS);
// 循环执行
scheduledThreadPool.scheduleAtFixedRate(() ->
System.out.println("delay 1 seconds, and excute every 3 seconds"),
1, 3, TimeUnit.SECONDS);
}
/**
* 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
* 因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。
*/
private void testFixedPool() {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(() -> {
try {
System.out.println(index);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
/**
* 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
* 线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。
*/
private void testCachePool() {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
cachedThreadPool.execute(() -> System.out.println(index)
);
}
}
}
自定义安全线程池
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @description:
* @author: yangdehong
* @version: 2018/1/19.
*/
public class MyThreadFactory implements ThreadFactory {
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
public MyThreadFactory(String prefix) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
namePrefix = "my-" + prefix + "-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
if (t.isDaemon()) // 是否守护线程
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY) // 是否是正常优先级
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @description:
* @author: yangdehong
* @version: 2018/1/19.
*/
public class MyExecutors {
public static ExecutorService newFixedThreadPool(int workerNum, String poolName) {
return java.util.concurrent.Executors.newFixedThreadPool(workerNum, new MyThreadFactory(poolName));
}
public static ExecutorService newFixedThreadPool(int workerNum, int maxNum, String poolName) {
return new java.util.concurrent.ThreadPoolExecutor(workerNum, maxNum,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
new MyThreadFactory(poolName));
}
public static ScheduledExecutorService newScheduledThreadPool(int workerNum, String poolName) {
return java.util.concurrent.Executors.newScheduledThreadPool(workerNum, new MyThreadFactory(poolName));
}
public static ExecutorService newCachedThreadPool(String poolName) {
return java.util.concurrent.Executors.newCachedThreadPool(new MyThreadFactory(poolName));
}
public static ExecutorService newSingleThreadExecutor(String poolName) {
return java.util.concurrent.Executors.newSingleThreadExecutor(new MyThreadFactory(poolName));
}
}
import java.util.concurrent.ExecutorService;
/**
* @description:
* @author: yangdehong
* @version: 2018/1/19.
*/
public class Test {
public static void main(String[] args) {
ExecutorService pool = MyExecutors.newFixedThreadPool(2, "test");
for (int i=0; i<10; i++) {
final int index = i;
pool.execute(() -> {
try {
System.out.println(index);
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
pool.shutdown();
}
}