Java線程池如何固定自身的大小
作者:佚名
Java線程池需要我們大家不斷的學習,其實我們需要不斷的學習才能更好的掌握相關(guān)的使用方式,下面我們就來詳細的看看。
Java線程池在我們學習的時候有很多的問題,其實在很多的問題我們都能在源代碼中找到我們想要的答案。希望大家有所收獲,首先我們來看看Java線程池大小的問題。
在使用線程池之前,必須知道如何去創(chuàng)建一個線程池,在Java5中,需要了解的是java.util.concurrent.Executors類的API,這個類提供大量創(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)建一個可重用固定線程數(shù)的線程池
- ExecutorService pool = Executors.newFixedThreadPool(2);
- //創(chuàng)建實現(xiàn)了Runnable接口對象,Thread對象當然也實現(xiàn)了Runnable接口
- Thread t1 = new MyThread();
- Thread t2 = new MyThread();
- Thread t3 = new MyThread();
- Thread t4 = new MyThread();
- Thread t5 = new MyThread();
- //將線程放入池中進行執(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)建實現(xiàn)了Runnable接口對象,Thread對象當然也實現(xiàn)了Runnable接口
- Thread t1 = new MyThread();
- Thread t2 = new MyThread();
- Thread t3 = new MyThread();
- Thread t4 = new MyThread();
- Thread t5 = new MyThread();
- //將線程放入池中進行執(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
以上就是對Java線程池的詳細介紹。
【編輯推薦】
責任編輯:張浩
來源:
互聯(lián)網(wǎng)