Search
β˜‚οΈ

Thread

Thread μ‹€ν–‰

β€’
Thread λ₯Ό extends ν•œλ‹€.
β€’
Runnable 을 implements ν•œλ‹€.
β€’
λ‘˜ λ‹€ run() 을 override ν•˜κ³  Thread 객체의 start() λ₯Ό ν˜ΈμΆœν•΄μ•Ό ν•œλ‹€.
β€’
start() 와 join() 의 μ°¨μ΄λŠ” λ¬΄μ—‡μΌκΉŒ?
Thread Pool
β€’
in a large-scale application, allocating and deallocating many thread objects creates a significant memory management overhead.
β—¦
λŒ€κ·œλͺ¨ μ–΄ν”Œλ¦¬μΌ€μ΄μ…˜μ—μ„œλŠ” ν• λ‹Ήκ³Ό μ œκ±°κ°€ λ©”λͺ¨λ¦¬ 관리 μ˜€λ²„ν—€λ“œλ₯Ό μ΄ˆλž˜ν•œλ‹€.
β€’
미리 μ“°λ ˆλ“œλ₯Ό 일정 수만큼 μ„€μ •ν•΄ λ†“λŠ” 것
β€’
Executors 와 ExecutorService 둜 μ„€μ • κ°€λŠ₯
β€’
Executors.newFixedThreadPool(int nThreads):
β—¦
This type of pool always has a specified number of threads running
β—¦
if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread.
β—¦
Tasks are submitted to the pool via an internal queue, which holds extra tasks whenever there are more active tasks than threads.
β—¦
μž₯점: μ˜€λ²„ν—€λ“œλ₯Ό 막아쀄 수 μžˆλ‹€.
β—¦
n개 만큼의 μ“°λ ˆλ“œλ₯Ό 생성
β€’
Executors.newCachedThreadPool()
β—¦
초기 μ“°λ ˆλ“œ κ°œμˆ˜λŠ” 0, κ°œμˆ˜λ³΄λ‹€ λ§Žμ€ μ–‘μ˜ μž‘μ—…μ΄ μš”μ²­λ˜λ©΄ μƒˆλ‘œμš΄ μ“°λ ˆλ“œλ₯Ό μƒμ„±ν•˜μ—¬ μž‘μ—… 처리
β—¦
μž‘μ—…μ΄ λλ‚œ μ“°λ ˆλ“œκ°€ 60초 λ™μ•ˆ μƒˆλ‘œμš΄ μž‘μ—… μš”μ²­μ΄ μ—†μœΌλ©΄ μ“°λ ˆλ“œλ₯Ό μ’…λ£Œν•˜κ³  μ“°λ ˆλ“œ ν’€μ—μ„œ 제거
start(), join()

submit(), execute()

execute()

β€’
μž‘μ—… 처리 κ²°κ³Όλ₯Ό λ°˜ν™˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.
β€’
μž‘μ—… 처리 도쀑 μ˜ˆμ™Έ λ°œμƒν•˜λ©΄ μŠ€λ ˆλ“œκ°€ μ’…λ£Œλ˜κ³  ν•΄λ‹Ή μŠ€λ ˆλ“œλŠ” μŠ€λ ˆλ“œν’€μ—μ„œ μ œκ±°ν•˜κ³ , μŠ€λ ˆλ“œν’€μ€ μž‘μ—… 처리λ₯Ό μœ„ν•΄ μƒˆλ‘œμš΄ μŠ€λ ˆλ“œλ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.

submit()

β€’
μž‘μ—… 처리 κ²°κ³Όλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
β€’
μž‘μ—… 처리 도쀑 μ˜ˆμ™Έκ°€ λ°œμƒν•˜λ”λΌλ„ μŠ€λ ˆλ“œλŠ” μ’…λ£Œλ˜μ§€ μ•Šκ³  λ‹€μŒ μž‘μ—…μ„ μœ„ν•΄Β μž¬μ‚¬μš©λ©λ‹ˆλ‹€.