1. 程式人生 > >Executor多線程框架使用

Executor多線程框架使用

tps and 初始化 實現 進行 rup package count ktr

轉載自:https://www.cnblogs.com/SimpleWu/p/9709272.html

以後再補全

常用接口:

1)創建固定數目線程的線程池:

public static ExecutorService newFixedThreadPool(int nThreads)

2)執行一個線程

void java.util.concurrent.Executor.execute(Runnable command)

3)查看當前活動線程個數

int java.util.concurrent.ThreadPoolExecutor.getActiveCount()

4)結束掉所有的線程

void java.util.concrrent.ExecutorService.shutdonw()

Executor在管理多個線程的時候會進行有效的安排。處理,比如創建的時候線程池裏有10個線程,加入實現線程超過10個Executor會進行有效的隊列阻塞和調度。對於我們開發者開說這是透明的,完全不需要關心它內部是怎麽進行的操作。

實例代碼:

package com.java.executor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class ExecutorTest {
    private static Integer count = 1; //數量
    
    private static boolean flag = true;//是否執行
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);//在連接池中初始化10個線程
        while(flag){
            if(count<=100){
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("執行 : " + count++);
                    }
                });
            }else{
                //判斷是否有活動線程
                if(((ThreadPoolExecutor)executorService).getActiveCount()==0){
                    executorService.shutdown();//結束所有線程
                    flag=false;
                    System.out.println("完成操作");
                }
            }
            try {
                Thread.sleep(100);//休息0.1秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

這是Executor簡單的使用方式,方便快捷,學習難度底,在這裏我們為什麽要休息0.1秒呢,在上面這段代碼上我們是沒有加鎖的,如果不休息在這段代碼上等count大於100的時候,線程還在活動中會導致線程沒有進行關閉,加上線程執行速度的飛快會超過我們需求,並且在爬蟲爬網頁的時候使用這麽塊的速度是很容易封IP的。

Executor多線程框架使用