JDK提供了一套Executor框架,可以幫助開發(fā)人員有效的使用線程池。

package com.wkcto.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 線程池的基本使用
*/
public class Test01 {
public static void main(String[] args) {
//創(chuàng)建有5個(gè)線程大小的線程池,
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
//向線程池中提交18個(gè)任務(wù),這18個(gè)任務(wù)存儲(chǔ)到線程池的阻塞隊(duì)列中, 線程池中這5個(gè)線程就從阻塞隊(duì)列中取任務(wù)執(zhí)行
for (int i = 0; i < 18; i++) {
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getId() + " 編號(hào)的任務(wù)在執(zhí)行任務(wù),開始時(shí)間: " + System.currentTimeMillis());
try {
Thread.sleep(3000); //模擬任務(wù)執(zhí)行時(shí)長
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}
package com.wkcto.threadpool;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 線程池的計(jì)劃任務(wù)
*/
public class Test02 {
public static void main(String[] args) {
//創(chuàng)建一個(gè)有調(diào)度功能的線程池
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
//在延遲2秒后執(zhí)行任務(wù), schedule( Runnable任務(wù), 延遲時(shí)長, 時(shí)間單位)
scheduledExecutorService.schedule(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getId() + " -- " + System.currentTimeMillis() );
}
}, 2, TimeUnit.SECONDS);
//以固定的頻率執(zhí)行任務(wù),開啟任務(wù)的時(shí)間是固定的, 在3秒后執(zhí)行任務(wù),以后每隔5秒重新執(zhí)行一次
/* scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getId() + "----在固定頻率開啟任務(wù)---" + System.currentTimeMillis());
try {
TimeUnit.SECONDS.sleep(3); //睡眠模擬任務(wù)執(zhí)行時(shí)間 ,如果任務(wù)執(zhí)行時(shí)長超過了時(shí)間間隔,則任務(wù)完成后立即開啟下個(gè)任務(wù)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 3, 2, TimeUnit.SECONDS);*/
//在上次任務(wù)結(jié)束后,在固定延遲后再次執(zhí)行該任務(wù),不管執(zhí)行任務(wù)耗時(shí)多長,總是在任務(wù)結(jié)束后的2秒再次開啟新的任務(wù)
scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getId() + "----在固定頻率開啟任務(wù)---" + System.currentTimeMillis());
try {
TimeUnit.SECONDS.sleep(3); //睡眠模擬任務(wù)執(zhí)行時(shí)間 ,如果任務(wù)執(zhí)行時(shí)長超過了時(shí)間間隔,則任務(wù)完成后立即開啟下個(gè)任務(wù)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 3, 2, TimeUnit.SECONDS);
}
}