Java 프로그래밍에서 스레드 풀의 기본 개념과 사용

5006 단어 Java스레드 탱크
1 스레드 탱크를 도입한 이유
라인의 생명 주기에는 창설, 준비, 운행, 막힘, 소각 단계가 포함되기 때문에 우리가 처리해야 할 임무의 수가 시간에 비해 우리는 스스로 몇 개의 라인을 만들어서 해당하는 임무를 처리할 수 있지만 대량의 임무가 있을 때 라인을 창설하고 소각하는 데 많은 비용이 필요하기 때문에 라인 탱크를 운용하는 이런 문제는 크게 완화되었다.
2 스레드 탱크의 사용
우리는 Executors 클래스가 우리에게 제공하는 정적 방법만 활용하면 해당하는 스레드 탱크를 만들 수 있다.

  public static ExecutorSevice newSingleThreadExecutor()

  public static ExecutorSevice newFixedThreadPool()

  public static ExecutorSevice newCachedThreadPool()

newSingleThreadExecutor는 단일 스레드를 포함하는 Executor로 되돌아와 여러 작업을 이 Exector에 맡길 때, 이 스레드가 한 작업을 처리한 후에 다음 작업을 처리합니다. 이 스레드에 이상이 발생하면 새로운 스레드가 대체됩니다.
newFixedThreadPool은 지정된 스레드를 포함하는 스레드 탱크를 되돌려줍니다. 만약 작업 수량이 스레드 수량보다 많으면, 작업이 완료될 때까지 기다릴 작업이 없습니다.
newCachedThreadPool은 사용자의 작업 수에 따라 해당하는 스레드를 만들어서 처리합니다. 이 스레드 탱크는 스레드 수를 제한하지 않고 JVM이 스레드를 만들 수 있는 수량에 전적으로 의존하여 메모리 부족을 초래할 수 있습니다.
실행 중인 작업을 run 방법에 넣으면 됩니다. Runnable 인터페이스의 실현 클래스를 스레드 탱크의 execute 방법에 전달하는 매개 변수는 다음과 같습니다.

Executor executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable(){
  public void run(){
    //   
 }
}
작업에 매개 변수를 전달해야 한다면, Runnable 인터페이스의 실현 클래스를 만들어서 완성할 수 있습니다.
3. 실례
(1):newSingleThreadExecutor
MyThread.java

publicclassMyThread extends Thread {
  @Override
  publicvoid run() {
    System.out.println(Thread.currentThread().getName() + " 。。。");
  }
}
TestSingleThreadExecutor.java
publicclassTestSingleThreadExecutor {
  publicstaticvoid main(String[] args) {
    // 
    ExecutorService pool = Executors. newSingleThreadExecutor();
    // Runnable ,Thread Runnable 
    Thread t1 = new MyThread();
    Thread t2 = new MyThread();
    Thread t3 = new MyThread();
    Thread t4 = new MyThread();
    Thread t5 = new MyThread();
    // 
    pool.execute(t1);
    pool.execute(t2);
    pool.execute(t3);
    pool.execute(t4);
    pool.execute(t5);
    // 
    pool.shutdown();
  }
}
결과 내보내기

pool-1-thread-1 。。。
pool-1-thread-1 。。。
pool-1-thread-1 。。。
pool-1-thread-1 。。。
pool-1-thread-1 。。。
(2):newFixedThreadPool
TestFixedThreadPool.Java

publicclass TestFixedThreadPool {
  publicstaticvoid main(String[] args) {
    // 
    ExecutorService pool = Executors.newFixedThreadPool(2);
    // Runnable ,Thread Runnable 
    Thread t1 = new MyThread();
    Thread t2 = new MyThread();
    Thread t3 = new MyThread();
    Thread t4 = new MyThread();
    Thread t5 = new MyThread();
    // 
    pool.execute(t1);
    pool.execute(t2);
    pool.execute(t3);
    pool.execute(t4);
    pool.execute(t5);
    // 
    pool.shutdown();
  }
}
결과 내보내기

pool-1-thread-1 。。。
pool-1-thread-2 。。。
pool-1-thread-1 。。。
pool-1-thread-2 。。。
pool-1-thread-1 。。。
(3): newCachedThreadPool
TestCachedThreadPool.java

publicclass TestCachedThreadPool {
  publicstaticvoid main(String[] args) {
    // 
    ExecutorService pool = Executors.newCachedThreadPool();
    // Runnable ,Thread Runnable 
    Thread t1 = new MyThread();
    Thread t2 = new MyThread();
    Thread t3 = new MyThread();
    Thread t4 = new MyThread();
    Thread t5 = new MyThread();
    // 
    pool.execute(t1);
    pool.execute(t2);
    pool.execute(t3);
    pool.execute(t4);
    pool.execute(t5);
    // 
    pool.shutdown();
  }
}
출력 결과:

pool-1-thread-2 。。。
pool-1-thread-4 。。。
pool-1-thread-3 。。。
pool-1-thread-1 。。。
pool-1-thread-5 。。。
(4):newScheduledThreadPool
TestScheduledThreadPoolExecutor.java

publicclass TestScheduledThreadPoolExecutor {
  publicstaticvoid main(String[] args) {
    ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
    exec.scheduleAtFixedRate(new Runnable() {// 
           @Override
           publicvoid run() {
              //throw new RuntimeException();
              System.out.println("================");
           }
         }, 1000, 5000, TimeUnit.MILLISECONDS);
    exec.scheduleAtFixedRate(new Runnable() {// , 
           @Override
           publicvoid run() {
              System.out.println(System.nanoTime());
           }
         }, 1000, 2000, TimeUnit.MILLISECONDS);
  }
}
결과 내보내기

================
8384644549516
8386643829034
8388643830710
================
8390643851383
8392643879319
8400643939383

좋은 웹페이지 즐겨찾기