4 자바 스레드 풀 스레드 풀 사용의 종류뿐만 아니라 역할과 장점은, 아직 알아?

다음과 같이 첫째, 질문이있다

new Thread() {
    @Override
    public void run() {
        // 业务逻辑
    }
}.start();

复制代码
1, 최초의 자주 만들고, 객체를 파괴 매우 많이 걸리는 것은 성능이다;
2, 경우보다 사용자가 더 큰 자원의 과도한 소비로 이어지는 것은 부족으로 인해 자원과 다운 타임의 우리의 서비스로 이어질 수있다;
3. 요약하면, 실제 개발에,이 작업은 실제로 바람직한 방법입니다.

둘째, 스레드 풀을 사용하는 장점은 무엇인가

1, 객체 생성을 줄이기 위해 스레드 풀에서 스레드의 활용을 강화하기 위해 파괴;
2, 효율적으로, 서버 리소스의 사용을 개선 인해 자원과 다른 문제의 부족으로 다운 타임을 방지하기 위해 스레드의 수를 스레드 풀을 제어 할 수 있습니다;

스레드 풀을 사용하는 세 가지 또는 네 가지 방법

1 newCachedThreadPool

풀에서 스레드의 수가 너무 큰 경우 스레드의 수, 그것은 새 스레드를 만들 수 있다면, 효과적으로, 여분의 스레드를 복구 할 수 있습니다, 스레드 풀을 만듭니다.
public static void method() throws Exception {
    ExecutorService executor = Executors.newCachedThreadPool();
    for (int i = 0; i < 5; i++) {
        final int index = i;
        Thread.sleep(1000);
        executor.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "  " + index);
            }
        });
    }
}

复制代码
결과
난 당신이, 분석에 의해 참조 실행 스레드에 의해 마무리에 시작할 수 있다고 생각 재사용을 스레드, 그리고 여분의 스레드를 생성하지 않습니다.
우리의 사업을 처리하는 데 시간이 좀 걸릴 것입니다 경우 때, 그래서 결과가 나타납니다 것을. 우리는 그것을 시뮬레이션 할 수 있습니다.
우리는 분명 지금 우리가 교대로 수행하는 데 몇 스레드를 필요로 볼 수 있습니다.
부적절한 :이 방법은 비즈니스 시나리오를 기반으로 우리의 사업을 처리 할 수 ​​있지만 자동으로 스레드의 수를 확장하지만, 많은 스레드는 우리가 통제 할 수없는 결손 처리하도록 취할 수있는 방법;
장점 : 두 번째 작업이 시작 때, 첫 번째 작업의 끝이 실행 된 경우, 다음 두 번째 작업은 첫 번째 작업으로 스레드를 생성-다시되며, 새 스레드를 다시 만들 스레드 재사용 율을 증가하지 않습니다 ;

2 인 newFixedThreadPool

이 방법 당신은 풀에서 스레드 수를 지정할 수 있습니다. 밤의 경우, 최대 목욕 집은 밖에서 기다리는 사람들 만의 뒤쪽으로, 목욕을 동시에 20 명을 수용 할 수 있습니다. 하드는 내부 마찰을 지르고 장면 만 출현을, 돌진하면 ...
첫 번째 스레드의 최대 용량을 테스트, 그것은 우리의 예측 결과가되지 않습니다.
public static void method_01() throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool(1);
    for (int i = 0; i < 10; i++) {
        Thread.sleep(1000);
        final int index = i;
        executor.execute(() -> {
            try {
                Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "  " + index);
        });
    }
    executor.shutdown();
}

复制代码
결과
그런 다음 결과를 보면 우리는 세 개의 스레드를 변경
장점 :이 통합 된 결과 문, 우리가 사용, 동료의 최대 스레드 가장 큰 타격을 제어하여 우리의 서버를 만들 수 있습니다 갑자기 안 걸릴 증가시킨다 적시 흐름을 보장 할 수 있도록 제어 할 수있는 스레드 인 newFixedThreadPool의 수 너무 많은 서버 자원.

3 인 newScheduledThreadPool

스레드 풀 타이밍 및 작업 실행의 주기성을 지원하기 위해, 우리는 작업의 실행 시간을 지연시킬 수 있습니다, 당신은 또한 반복주기 작업에 대한 시간을 설정할 수 있습니다. 스레드 풀 방법은 다음과 같은 두 가지 지연이 있습니다.
  • scheduleAtFixedRate
테스트 1
public static void method_02() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
    executor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            long start = new Date().getTime();
            System.out.println("scheduleAtFixedRate 开始执行时间:" +
                    DateFormat.getTimeInstance().format(new Date()));
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            long end = new Date().getTime();
            System.out.println("scheduleAtFixedRate 执行花费时间=" + (end - start) / 1000 + "m");
            System.out.println("scheduleAtFixedRate 执行完成时间:" + DateFormat.getTimeInstance().format(new Date()));
            System.out.println("======================================");
        }
    }, 1, 5, TimeUnit.SECONDS);
}

复制代码
결과
시험 두
요약 : 두 가지 방법 위의 다른 장소 간격이 작업의 실행 시간보다 큰 경우, 작업이 실행시의 영향을받지 않습니다, 작업의 실행 시간입니다. 간격이 작업의 실행 시간보다 작은 경우, 위임의 끝이 즉시 구현 될 것입니다 후 후, 지금까지의 간격은 중단 될 것입니다.
  • scheduleWithFixedDelay
테스트 1
public static void method_03() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
    executor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            long start = new Date().getTime();
            System.out.println("scheduleWithFixedDelay 开始执行时间:" +
                    DateFormat.getTimeInstance().format(new Date()));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            long end = new Date().getTime();
            System.out.println("scheduleWithFixedDelay执行花费时间=" + (end - start) / 1000 + "m");
            System.out.println("scheduleWithFixedDelay执行完成时间:"
                    + DateFormat.getTimeInstance().format(new Date()));
            System.out.println("======================================");
        }
    }, 1, 2, TimeUnit.SECONDS);
}

复制代码
결과
시험 두
public static void method_03() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
    executor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            long start = new Date().getTime();
            System.out.println("scheduleWithFixedDelay 开始执行时间:" +
                    DateFormat.getTimeInstance().format(new Date()));
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            long end = new Date().getTime();
            System.out.println("scheduleWithFixedDelay执行花费时间=" + (end - start) / 1000 + "m");
            System.out.println("scheduleWithFixedDelay执行完成时间:"
                    + DateFormat.getTimeInstance().format(new Date()));
            System.out.println("======================================");
        }
    }, 1, 2, TimeUnit.SECONDS);
}

复制代码
결과
요약 : 동일 scheduleWithFixedDelay 동일한 시험 방법으로, 시간 간격을 측정 할 수 scheduleWithFixedDelay 태스크의 실행이 영향의 시간 길이에 의해 영향을받지 않는다.

4 newSingleThreadExecutor

이는 단일 스레드 풀은, 실행 스레드에 의해 마무리에 시작입니다.
public static void method_04() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    for (int i = 0; i < 5; i++) {
        final int index = i;
        executor.execute(() -> {
            try {
                Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "   " + index);
        });
    }
    executor.shutdown();
}

复制代码
결과

스레드 풀의 넷째, 역할

스레드 풀의 주요 역할은 시스템 성능 및 사용을 개선하는 것입니다. 처음에 언급 된 기사, 우리는 사용자의 많은 양의, 그것은 생성하고있는 thread 소비 성능을 생성 및 파괴에 서버를 일으키는 스레드를 파괴하는 행동을 많이 생산한다면, 스레드를 만드는 가장 쉬운 방법을 사용하는 경우 처리 시간과 실제 비즈니스 성과의 비용보다 더. 이 스레드 풀은 이러한 문제가 발생 해결하는 것입니다.
마찬가지로,이 때문에 데이터베이스에 자주 접속 등의 데이터베이스 연결 풀 한 많은 디자인 아이디어,하지만 연결을 생성하는 성능이 걸리는 일이 모든 데이터베이스 연결 풀 나타났다.

최종적으로

나는 데이터 컴파일이 내부에있을 것입니다, 기사가 업데이트 될 모든 사람의 관심 공공 무리 번호 [프로그래머], 환영합니다.

추천

출처juejin.im/post/5db28898e51d452a161df452