Search
Duplicate
โ˜‚๏ธ

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()

โ€ข
์ž‘์—… ์ฒ˜๋ฆฌ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
โ€ข
์ž‘์—… ์ฒ˜๋ฆฌ ๋„์ค‘ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜๋”๋ผ๋„ ์Šค๋ ˆ๋“œ๋Š” ์ข…๋ฃŒ๋˜์ง€ ์•Š๊ณ  ๋‹ค์Œ ์ž‘์—…์„ ์œ„ํ•ดย ์žฌ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.