多線程——newFixedThreadPool線程池


newFixedThreadPool線程池:

理解:
  1.固定線程數的線程池。
  2.通過Executors中的靜態方法創建:
      public static ExecutorService newFixedThreadPool(int nThreads)或者
      public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory)兩種方式。
  3.返回的是ExecutorService對象線程池,例如:ExecutorService executorService = Executors.newFixedThreadPool(10)。
例子:
/**
 * 線程池,實現Runnable接口
 * @author Administrator
 *
 */
public class ThreadPoolRunnable implements Runnable{
    public void run(){
        System.out.println(Thread.currentThread().getName()+"線程");
    }
}
/**
 * 實現Callable線程池
 * @author Administrator
 *
 */
public class ThreadPoolCallable implements Callable<String>{
    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName()+"開始執行Callable接口.......");
        return "線程執行完畢!";
    }
}

 

//線程池測試類
public class TestThreadPoolRunnable {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        threadRunnable(5, 10);
        threadCallable(3, 10);
    }

    /**
     * 實現Runnable接口線程池
     * 
     * @param a
     *            創建線程數量
     * @param b
     *            線程池總數
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static void threadRunnable(int a, int b) throws InterruptedException, ExecutionException {
        // 創建線程池
        ExecutorService executorService = Executors.newFixedThreadPool(b);
        for (int i = 0; i < a; i++) {
            // 從線程池中調用線程
            executorService.submit(new ThreadPoolRunnable());
        }
    }

    /**
     * 實現Callable線程池
     * 
     * @param a
     *            創建線程數
     * @param b
     *            線程池總數
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static void threadCallable(int a, int b) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(b);
        for (int i = 0; i < a; i++) {
            Future<String> s = executorService.submit(new ThreadPoolCallable());
            System.out.println(s.get());
        }
    }
}
結果:
pool-1-thread-1線程
pool-1-thread-3線程
pool-1-thread-2線程
pool-1-thread-5線程
pool-1-thread-4線程
pool-2-thread-1開始執行Callable接口.......
線程執行完畢!
pool-2-thread-2開始執行Callable接口.......
線程執行完畢!
pool-2-thread-3開始執行Callable接口.......
線程執行完畢!

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM