新聞中心
Java線(xiàn)程池在我們學(xué)習(xí)的時(shí)候有很多的問(wèn)題,其實(shí)在很多的問(wèn)題我們都能在源代碼中找到我們想要的答案。希望大家有所收獲,首先我們來(lái)看看Java線(xiàn)程池大小的問(wèn)題。

創(chuàng)新互聯(lián)建站從2013年成立,是專(zhuān)業(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)系電話(huà):028-86922220
在使用線(xiàn)程池之前,必須知道如何去創(chuàng)建一個(gè)線(xiàn)程池,在Java5中,需要了解的是java.util.concurrent.Executors類(lèi)的API,這個(gè)類(lèi)提供大量創(chuàng)建連接池的靜態(tài)方法,是必須掌握的。
固定大小的Java線(xiàn)程池
Java線(xiàn)程池代碼
- import java.util.concurrent.Executors;
- import java.util.concurrent.ExecutorService;
- /**
- * Java線(xiàn)程:線(xiàn)程池-
- *
- * @author Administrator 2009-11-4 23:30:44
- */
- public class Test {
- public static void main(String[] args) {
- //創(chuàng)建一個(gè)可重用固定線(xiàn)程數(shù)的線(xiàn)程池
- 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();
- //將線(xiàn)程放入池中進(jìn)行執(zhí)行
- pool.execute(t1);
- pool.execute(t2);
- pool.execute(t3);
- pool.execute(t4);
- pool.execute(t5);
- //關(guān)閉線(xià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線(xiàn)程:線(xiàn)程池-
- *
- * @author Administrator 2009-11-4 23:30:44
- */
- public class Test {
- public static void main(String[] args) {
- //創(chuàng)建一個(gè)可重用固定線(xiàn)程數(shù)的線(xiàn)程池
- 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();
- //將線(xiàn)程放入池中進(jìn)行執(zhí)行
- pool.execute(t1);
- pool.execute(t2);
- pool.execute(t3);
- pool.execute(t4);
- pool.execute(t5);
- //關(guān)閉線(xiàn)程池
- pool.shutdown();
- }
- }
- class MyThread extends Thread{
- @Override
- public void run() {
- System.out.println(Thread.currentThread().getName()+
"正在執(zhí)行。");- }
Java線(xiàn)程池代碼
- 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線(xiàn)程池的詳細(xì)介紹。
分享名稱(chēng):Java線(xiàn)程池如何固定自身的大小
標(biāo)題來(lái)源:http://www.dlmjj.cn/article/dpdepis.html


咨詢(xún)
建站咨詢(xún)
