您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)Java中怎么固定線程池大小,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
固定大小的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)建一個可重用固定線程數(shù)的線程池
ExecutorService pool = Executors.newFixedThreadPool(2);
//創(chuàng)建實(shí)現(xiàn)了Runnable接口對象,Thread對象當(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)建一個可重用固定線程數(shù)的線程池
ExecutorService pool = Executors.newFixedThreadPool(2);
//創(chuàng)建實(shí)現(xiàn)了Runnable接口對象,Thread對象當(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
看完上述內(nèi)容,你們對Java中怎么固定線程池大小有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。