Java 프로그래밍에서 스레드 풀의 기본 개념과 사용
라인의 생명 주기에는 창설, 준비, 운행, 막힘, 소각 단계가 포함되기 때문에 우리가 처리해야 할 임무의 수가 시간에 비해 우리는 스스로 몇 개의 라인을 만들어서 해당하는 임무를 처리할 수 있지만 대량의 임무가 있을 때 라인을 창설하고 소각하는 데 많은 비용이 필요하기 때문에 라인 탱크를 운용하는 이런 문제는 크게 완화되었다.
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):newFixedThreadPoolTestFixedThreadPool.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): newCachedThreadPoolTestCachedThreadPool.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):newScheduledThreadPoolTestScheduledThreadPoolExecutor.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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.