Thread 에 대해서는 아래 참고 포스팅 참고 바란다.
Thread를 다른 Thread 와 관계를 없애기 위한 ThreadLocal (참고포스팅 참고),
혹은 일정 시간동안 Thread 를 멈추게하는 sleep (참고포스팅 참고),
혹은 count 를 두고 그동안 Thread 를 얼려두는 countDownLatch(참고포스팅참고)
등이 있지만,
이것들은 각각 하나의 Thread를 띄우기 위함이고,
반대로 작업의 주체가 되는 Thread를 여러개를 동시에 띄울수도 있다.
멀티 쓰레드에 대해서는 이미 다룬 글이 있고 실습을 위해 본 포스팅을 작성한다.
개념에 대해서는 아래 참고 포스팅을 참고 바란다.
바로 예제 코드를 만나보는것이 빠른 이해에 도움이 될것이다.
public static void main(String[] args) throws InterruptedException { BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(1); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 5, 100, TimeUnit.SECONDS, blockingQueue); Runnable task = new Task(); for (int i = 0; i < 3; i++) { threadPoolExecutor.execute(task); } System.out.println("쓰레드 콜 종료"); } static class Task implements Runnable { int num = 0; @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + ", num=" + num++); } } } |
노란 부분이 ThreadPoolExecutor를 사용하여 pool을 만들어준다.
각 파라미터에 대한 설명은 아래와 같다.
* @param corePoolSize the number of threads to keep in the pool, even * if they are idle, unless {@code allowCoreThreadTimeOut} is set * @param maximumPoolSize the maximum number of threads to allow in the * pool * @param keepAliveTime when the number of threads is greater than * the core, this is the maximum time that excess idle threads * will wait for new tasks before terminating. * @param unit the time unit for the {@code keepAliveTime} argument * @param workQueue the queue to use for holding tasks before they are * executed. This queue will hold only the {@code Runnable} * tasks submitted by the {@code execute} method. |
간단하게 보면
corePoolSize - corePoolSize 풀에 보관할 스레드 수
maximumPoolSize - maximumPoolSize 허용되는 최대 스레드 수
keepAliveTime - 스레드가 발생하는 최대 시간
unit - Param의 단위
workQueue - 작업 완료 전 대기열
라고 생각하면 된다.
위와 같은 코드를 짜고 실행해보면 지금처럼 나온다.
pool-1-thread-1, num=0 pool-1-thread-1, num=2 pool-1-thread-1, num=3 pool-1-thread-1, num=4 pool-1-thread-2, num=1 pool-1-thread-2, num=6 pool-1-thread-2, num=7 pool-1-thread-2, num=8 pool-1-thread-2, num=9 쓰레드 콜 종료 pool-1-thread-2, num=10 pool-1-thread-1, num=5 pool-1-thread-2, num=11 pool-1-thread-2, num=12 pool-1-thread-2, num=13 pool-1-thread-2, num=14 |
순서없이, 구분없이, 차례없이 결과가 이렇게 나오고 다시 돌리면 당연히 또 섞여서 누가 먼저인지 모르는 그런 출력이 된다.
3개의 Thread가 각각 1에서 5까지 의 출력을 하는것이니 이런 결과가 나온다.
참고 포스팅
https://thenicesj.tistory.com/492
Thread란? (process비교)
먼저 thread 에 알기 전보다 알아야할 것이 있다. 그는 바로 프로세스라는것이고 프로세스와 thread 에 차이를 알아본다. 프로세스(process)란? 프로세스(process)란 단순히 실행 중인 프로그램(program)이
thenicesj.tistory.com
https://thenicesj.tistory.com/296
delay 설정하기 (Thread.sleep)
코딩을 하다보면 일정 시간 잠깐 정지, delay를 해야할 경우가 있다. 파이썬에서는 간단하게 time.sleep(10) 이렇게 지정을 해주면 되지만 자바에서는 thread 단에서 잡아줘야한다. 코드는 다음과 같다.
thenicesj.tistory.com
https://thenicesj.tistory.com/717
ThreadLocal (동시성문제) 사용법 및 주의사항
이전 포스팅에서 Thread 사용법에 대해서 다룬적이 있다. 자세한 내용은 아래 참고 포스팅 참고 바란다. 하지만 대량 트래픽이 존재하는 서비스에서 매번 발생하는 문제. 바로 동시성 이슈 이다.
thenicesj.tistory.com
https://thenicesj.tistory.com/718
CountDownLatch (다른 쓰레드 대기)
이전 포스팅에서 Thread 간에 동시성 이슈에 대해 다룬 글이 있다. 자세한 내용은 참고 포스팅 참고 바란다. Thread 를 생성해서 사용할때 별도의 쓰레드 공간을 만들어서 사용하기 위해서는 아래
thenicesj.tistory.com
https://thenicesj.tistory.com/653
Multi-thread
쓰레드에 대해서 사용을 할때 멀티 쓰레드에 대한 내용을 다뤄보려고 한다. Thread 에 대한 기본적인 내용은 아래 참고 포스팅 참고 바란다. 멀티 쓰레딩이란 아래 그림을 보면 이해가 쉬울 것이
thenicesj.tistory.com
'IT > Java' 카테고리의 다른 글
Java Stream 으로 두 List 비교 (22) | 2024.01.27 |
---|---|
deleteAll(), deleteAllInBatch(), deleteInBatch() (22) | 2024.01.26 |
Java 에서 Http 통신 방식 3가지(RestTemplate, WebClient, OpenFeign) (9) | 2024.01.20 |
JPA메서드 save 와 saveAll 비교 (11) | 2024.01.19 |
Servlet 이란? (JSP 와 비교) (28) | 2024.01.17 |
댓글