新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
Java線程池如何固定自身的大小
Java線程池在我們學(xué)習(xí)的時(shí)候有很多的問(wèn)題,其實(shí)在很多的問(wèn)題我們都能在源代碼中找到我們想要的答案。希望大家有所收獲,首先我們來(lái)看看Java線程池大小的問(wèn)題。

創(chuàng)新互聯(lián)建站從2013年成立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元伽師做網(wǎng)站,已為上家服務(wù),為伽師各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220
在使用線程池之前,必須知道如何去創(chuàng)建一個(gè)線程池,在Java5中,需要了解的是java.util.concurrent.Executors類的API,這個(gè)類提供大量創(chuàng)建連接池的靜態(tài)方法,是必須掌握的。
固定大小的Java線程池
Java線程池代碼
- import java.util.concurrent.Executors;
- import java.util.concurrent.ExecutorService;
- /**
- * Java線程:線程池-
- *
- * @author Administrator 2009-11-4 23:30:44
- */
- public class Test {
- public static void main(String[] args) {
- //創(chuàng)建一個(gè)可重用固定線程數(shù)的線程池
- ExecutorService pool = Executors.newFixedThreadPool(2);
- //創(chuàng)建實(shí)現(xiàn)了Runnable接口對(duì)象,Thread對(duì)象當(dāng)然也實(shí)現(xiàn)了Runnable接口
- Thread t1 = new MyThread();
- Thread t2 = new MyThread();
- Thread t3 = new MyThread();
- Thread t4 = new MyThread();
- Thread t5 = new MyThread();
- //將線程放入池中進(jìn)行執(zhí)行
- pool.execute(t1);
- pool.execute(t2);
- pool.execute(t3);
- pool.execute(t4);
- pool.execute(t5);
- //關(guān)閉線程池
- pool.shutdown();
- }
- }
- class MyThread extends Thread{
- @Override
- public void run() {
- System.out.println(Thread.currentThread().getName()+
"正在執(zhí)行。");- }
- }
- import java.util.concurrent.Executors;
- import java.util.concurrent.ExecutorService;
- /**
- * Java線程:線程池-
- *
- * @author Administrator 2009-11-4 23:30:44
- */
- public class Test {
- public static void main(String[] args) {
- //創(chuàng)建一個(gè)可重用固定線程數(shù)的線程池
- ExecutorService pool = Executors.newFixedThreadPool(2);
- //創(chuàng)建實(shí)現(xiàn)了Runnable接口對(duì)象,Thread對(duì)象當(dāng)然也實(shí)現(xiàn)了Runnable接口
- Thread t1 = new MyThread();
- Thread t2 = new MyThread();
- Thread t3 = new MyThread();
- Thread t4 = new MyThread();
- Thread t5 = new MyThread();
- //將線程放入池中進(jìn)行執(zhí)行
- pool.execute(t1);
- pool.execute(t2);
- pool.execute(t3);
- pool.execute(t4);
- pool.execute(t5);
- //關(guān)閉線程池
- pool.shutdown();
- }
- }
- class MyThread extends Thread{
- @Override
- public void run() {
- System.out.println(Thread.currentThread().getName()+
"正在執(zhí)行。");- }
Java線程池代碼
- pool-1-thread-1正在執(zhí)行。
- pool-1-thread-1正在執(zhí)行。
- pool-1-thread-1正在執(zhí)行。
- pool-1-thread-1正在執(zhí)行。
- pool-1-thread-2正在執(zhí)行。
- Process finished with exit code 0
以上就是對(duì)Java線程池的詳細(xì)介紹。
文章題目:Java線程池如何固定自身的大小
本文鏈接:http://m.fisionsoft.com.cn/article/dpdepis.html


咨詢
建站咨詢
