Java線程池在使用中的問題解疑
Java線程池需要我們不斷的學(xué)習(xí),其實(shí)我們?cè)谑褂玫臅r(shí)候還是有不少問題需要我們解決。我們實(shí)現(xiàn)了一個(gè)簡單的Java線程池?,F(xiàn)在我們就可以使用它了,下面的代碼做了一個(gè)簡單的示例:
Java代碼
- public class SimpleTaskTest extends Task {
- @Override
- public void deal() {
- // do something
- }
- public static void main(String[] args) throws InterruptedException {
- ThreadPoolService service = new ThreadPoolService();
- service.start();
- // 執(zhí)行十次任務(wù)
- for (int i = 0; i < 10; i++) {
- service.runTask(new SimpleTaskTest());
- }
- // 睡眠1秒鐘,等待所有任務(wù)執(zhí)行完畢
- Thread.sleep(1000);
- service.stop();
- }
- }
- public class SimpleTaskTest extends Task {
- @Override
- public void deal() {
- // do something
- }
- public static void main(String[] args) throws InterruptedException {
- ThreadPoolService service = new ThreadPoolService();
- service.start();
- // 執(zhí)行十次任務(wù)
- for (int i = 0; i < 10; i++) {
- service.runTask(new SimpleTaskTest());
- }
- // 睡眠1秒鐘,等待所有任務(wù)執(zhí)行完畢
- Thread.sleep(1000);
- service.stop();
- }
- }
當(dāng)然,我們實(shí)現(xiàn)的是最簡單的,這里只是為了演示Java線程池的實(shí)現(xiàn)原理。在實(shí)際應(yīng)用中,根據(jù)情況的不同,可以做很多優(yōu)化。比如:
調(diào)整任務(wù)隊(duì)列的規(guī)則,給任務(wù)設(shè)置優(yōu)先級(jí),級(jí)別高的任務(wù)優(yōu)先執(zhí)行。
動(dòng)態(tài)維護(hù)Java線程池,當(dāng)待執(zhí)行任務(wù)數(shù)量較多時(shí),增加線程的數(shù)量,加快任務(wù)的執(zhí)行速度;當(dāng)任務(wù)較少時(shí),回收一部分長期閑置的Java線程池,減少對(duì)系統(tǒng)資源的消耗。
事實(shí)上Java5.0及以上版本已經(jīng)為我們提供了線程池功能,無需再重新實(shí)現(xiàn)。這些類位于java.util.concurrent包中。
Executors類提供了一組創(chuàng)建Java線程池對(duì)象的方法,常用的有一下幾個(gè):
Java代碼
- public static ExecutorService newCachedThreadPool() {
- // other code
- }
- public static ExecutorService newFixedThreadPool(int nThreads) {
- // other code
- }
- public static ExecutorService newSingleThreadExecutor() {
- // other code
- }
- public static ExecutorService newCachedThreadPool() {
- // other code
- }
- public static ExecutorService newFixedThreadPool(int nThreads) {
- // other code
- }
- public static ExecutorService newSingleThreadExecutor() {
- // other code
- }
newCachedThreadPool()方法創(chuàng)建一個(gè)動(dòng)態(tài)的線程池,其中線程的數(shù)量會(huì)根據(jù)實(shí)際需要來創(chuàng)建和回收,適合于執(zhí)行大量短期任務(wù)的情況;newFixedThreadPool(int nThreads)方法創(chuàng)建一個(gè)包含固定數(shù)量線程對(duì)象的Java線程池,nThreads代表要?jiǎng)?chuàng)建的線程數(shù),如果某個(gè)線程在運(yùn)行的過程中因?yàn)楫惓6K止了,那么一個(gè)新的線程會(huì)被創(chuàng)建和啟動(dòng)來代替它;而newSingleThreadExecutor()方法則只在線程池中創(chuàng)建一個(gè)線程,來執(zhí)行所有的任務(wù)。
【編輯推薦】