자바 스 레 드 공장 을 이용 하여 스 레 드 탱크 의 실현 예 를 감시 하 다.

ThreadFactory
스 레 드 탱크 의 스 레 드 는 어디에서 옵 니까?바로 ThreadFoctory 입 니 다.

public interface ThreadFactory {
    Thread newThread(Runnable r);
}
Threadfactory 에 인터페이스 가 있 습 니 다.스 레 드 탱크 에 스 레 드 를 만 들 려 면 이 방법 을 사용 하고 스 레 드 공장 을 사용자 정의 할 수 있 습 니 다.

public class ThreadfactoryText {
    public static void main(String[] args) {
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                int num=new Random().nextInt(10);
                System.out.println(Thread.currentThread().getId()+"--"+System.currentTimeMillis()+"--  "+num);
                try {
                    TimeUnit.SECONDS.sleep(num);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        //                         
        ExecutorService executorService=new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t=new Thread(r);
                t.setDaemon(true);//       ,        ,           
                System.out.println("     "+t);
                return t;
            }
        });
        //      
        for (int i = 0; i < 5; i++) {
            executorService.submit(runnable);
        }
    }
}

스 레 드 가 다섯 개 이상 의 작업 을 제출 할 때 스 레 드 탱크 는 기본적으로 이상 을 던 집 니 다.
모니터링 스 레 드 탱크
ThreadPoolExcutor 는 스 레 드 탱크 를 감시 하 는 방법 을 제공 합 니 다.

int getActiveCount()//               
long getCompletedTaskCount()//           
int getCorePoolSize()//          
int getLargestPoolSize() //                
int getMaximumPoolSize()//          
int getPoolSize()//      
BlockingQueue<Runnable> getQueue()//      
long getTaskCount()//           

public class Text {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getId() + "      --" + System.currentTimeMillis());
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        //                       DiscardPolicy  
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(2, 5, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5),Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());
        //      
        for (int i = 0; i < 30; i++) {
            executorService.submit(runnable);
            System.out.println("         "+executorService.getCorePoolSize()+",     :"+executorService.getMaximumPoolSize()+",       :"+executorService.getPoolSize()+"     :"+executorService.getActiveCount()+",    :"+executorService.getTaskCount()+"     :"+executorService.getCompletedTaskCount()+"     :"+executorService.getQueue().size());
            TimeUnit.MILLISECONDS.sleep(500);
        }
        System.out.println("-------------------");
        while (executorService.getActiveCount()>=0)//          
        {
          System.out.println("         "+executorService.getCorePoolSize()+",     :"+executorService.getMaximumPoolSize()+",       :"+executorService.getPoolSize()+"     :"+executorService.getActiveCount()+",    :"+executorService.getTaskCount()+"     :"+executorService.getCompletedTaskCount()+"     :"+executorService.getQueue().size());
            Thread.sleep(1000);// 1     
        }

    }
}
스 레 드 탱크 크기 가 핵심 스 레 드 수 에 이 르 면 스 레 드 는 대기 열 에 놓 입 니 다.스 레 드 탱크 대기 열 이 가득 차 면 새 스 레 드 가 열 립 니 다.현재 스 레 드 크기 가 최대 스 레 드 수 에 이 르 렀 을 때 대기 열 이 가득 찼 습 니 다.다시 제출 하면 DiscardPolicy 정책 을 실행 하고 처리 할 수 없 는 작업 을 버 립 니 다.마지막 30 개의 작업 은 15 개 만 남 았 습 니 다.

원 리 는 그림 과 같다.

확장 스 레 드 탱크
모든 작업 의 시작 과 종료 시간 을 감시 하거나 다른 증강 기능 을 사용자 정의 하 는 등 스 레 드 탱크 를 확장 해 야 할 때 도 있다.
Thread PoolExecutor 스 레 드 탱크 는 두 가지 방법 을 제공 합 니 다.

protected void beforeExecute(Thread t, Runnable r) { }
protected void afterExecute(Runnable r, Throwable t) { }
스 레 드 탱크 는 어떤 작업 을 수행 하기 전에 beforeExecute()방법 을 실행 하고 실행 후 after Execute()방법 을 호출 합 니 다.
ThreadPoolExecutor 소스 코드 를 보십시오.이 클래스 에서 내부 클래스 Worker 를 정 의 했 습 니 다.ThreadPoolExecutor 스 레 드 탱크 의 작업 스 레 드 는 Worker 클래스 의 인 스 턴 스 입 니 다.Worker 인 스 턴 스 는 실행 할 때 beforeExecute 와 after Execute 방법 을 호출 합 니 다.

public void run() {
            runWorker(this);
}
final void runWorker(Worker w) {
                try {
                    beforeExecute(wt, task);
                    try {
                        task.run();
                        afterExecute(task, null);
                    } catch (Throwable ex) {
                        afterExecute(task, ex);
                        throw ex;
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
    }      
일부 코드 가 생략 되 었 습 니 다.스 레 드 가 실행 되 기 전에 beforeExecute 를 호출 하고 실행 후 after Execute 방법 을 호출 합 니 다.
확장 스 레 드 탱크 예제

package com;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Text07 {
    public static void main(String[] args) {

        //                ThreadPoolExecutor,        
        ExecutorService threadPoolExecutor=
 new ThreadPoolExecutor(5,5,0, TimeUnit.SECONDS,new LinkedBlockingDeque<>()){
     //          
     @Override
     protected void beforeExecute(Thread t, Runnable r) {
         System.out.println(t.getId()+"        "+((Mytask)r).name);
     }
     //          
     @Override
     protected void afterExecute(Runnable r, Throwable t) {
         System.out.println(((Mytask)r).name+"    ");
     }
     //     
     @Override
     protected void terminated() {
         System.out.println("     ");
     }
 };
        for (int i = 0; i < 5; i++) {
            Mytask mytask=new Mytask("Thread"+i);
            threadPoolExecutor.execute(mytask);
        }
    }
    private  static  class  Mytask implements Runnable
    {
        private  String name;

        public  Mytask(String name)
        {
            this.name=name;
        }
        @Override
        public void run() {
            System.out.println(name+"     "+Thread.currentThread().getId());
            try {
                Thread.sleep(1000);//      
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

최적화 스 레 드 탱크 크기
스 레 드 탱크 의 크기 는 시스템 성능 에 어느 정도 영향 을 미 칩 니 다.너무 크 거나 너무 작 아 도 시스템 의 가장 좋 은 성능 을 발휘 할 수 없습니다.매우 정확 할 필요 가 없습니다.크 거나 작 지 않 으 면 됩 니 다.일반적으로 스 레 드 탱크 의 크기 는 야 오 가 CPU 수량 을 고려 합 니 다.
스 레 드 탱크 크기=CPU 수량*대상 CPU 사용률*(1+대기 시간 과 계산 시간의 비례)
스 레 드 풀 잠 금
스 레 드 탱크 가 실 행 될 때 작업 A 가 실 행 될 때 작업 B 를 제출 했 습 니 다.작업 B 는 스 레 드 탱크 에 추 가 된 대기 열 입 니 다.A 의 끝 에 B 의 실행 결과 가 필요 하고 B 스 레 드 가 A 스 레 드 가 실 행 될 때 까지 기 다 려 야 한다 면 다른 모든 작업 스 레 드 가 대기 상태 에 있 을 수 있 습 니 다.이 작업 들 이 차단 대기 열 에서 실 행 될 때 까지 기 다 려 야 합 니 다.스 레 드 탱크 에 차단 대기 열 을 처리 할 수 있 는 스 레 드 가 없 으 면 잠 금 이 되 기 를 기다 리 고 있 습 니 다.
서로 의존 하 는 임무 가 아니 라 스 레 드 탱크 에 서로 독립 된 임 무 를 제출 하기에 적합 하 며,서로 의존 하 는 임무 에 대해 서 는 각각 다른 스 레 드 탱크 에 제출 하여 처리 하 는 것 을 고려 할 수 있 습 니 다.
스 레 드 탱크 이상 정보 캡 처

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Text09 {
    public static void main(String[] args) {
        //     
        ExecutorService executorService=new ThreadPoolExecutor(5,5,0, TimeUnit.SECONDS,new SynchronousQueue<>());
        //                 
        for (int i = 0; i <5 ; i++) {
            executorService.submit(new Text(10,i));
        }

    }
    private  static class  Text implements  Runnable
    {
        private  int x;
        private  int y;
        public  Text(int x,int y)
        {
            this.x=x;
            this.y=y;
        }
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"  x/y    "+x+"/"+y+"="+(x/y));
        }
    }
}

네 가지 결과 만 볼 수 있 습 니 다.실제 적 으로 스 레 드 탱크 에 다섯 가지 임 무 를 제출 했 습 니 다.그러나 i=0 시 산술 이상 이 발생 했 습 니 다.스 레 드 탱크 가 이 이상 을 먹 어서 우 리 는 이 이상 에 대해 아무것도 모 릅 니 다.
해결 방법:
1.submit 를 execute 로 변경

2.스 레 드 탱크 확장,submit 포장

package com;

import java.util.concurrent.*;

public class Text09 {
    public static void main(String[] args) {
        //                
        ExecutorService executorService=new TranceThreadPoorExcuter(5,5,0, TimeUnit.SECONDS,new SynchronousQueue<>());
        //                 
        for (int i = 0; i <5 ; i++) {
            executorService.submit(new Text(10,i));
        }

    }
    public  static class  Text implements  Runnable
    {
        public  int x;
        public  int y;
        public  Text(int x,int y)
        {
            this.x=x;
            this.y=y;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"  x/y    "+x+"/"+y+"="+(x/y));
        }
    }
    //         TranceThreadPoorExcuter    
    private  static  class  TranceThreadPoorExcuter extends  ThreadPoolExecutor
    {

        public TranceThreadPoorExcuter(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
            super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        }
        //                              Exception
        public  Runnable warp(Runnable r,Exception e)
        {
            return new Runnable() {
                @Override
                public void run() {

                    try {
                        r.run();
                    }
                    catch (Exception e1)
                    {
                        e.printStackTrace();
                        throw e1;
                    }
                }
            };
        }
        //  submit  
        @Override
        public Future<?> submit(Runnable task) {
            return super.submit(warp(task,new Exception("      ")));
        }
        //     excute  
    }
}

이 방법 은 사용자 정의 스 레 드 탱크 를 사용 하여 스 레 드 탱크 의 submit 방법 을 다시 작성 합 니 다.submit 방법 에서 들 어 올 작업 매개 변 수 를 이상 정 보 를 캡 처 하 는 기능 을 가지 고 있 으 면 스 레 드 탱크 이상 을 캡 처 할 수 있 습 니 다.
자바 가 스 레 드 공장 을 이용 하여 스 레 드 탱크 를 감시 하 는 실현 사례 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 자바 스 레 드 공장 모니터링 스 레 드 탱크 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 지원 을 바 랍 니 다!

좋은 웹페이지 즐겨찾기