Day19 - jeremy0405/Codesquad_CS GitHub Wiki
๋น๋๊ธฐ๋ ํน์ ๋ก์ง์ ์คํ์ด ๋๋ ๋๊น์ง ๊ธฐ๋ค๋ฆฌ์ง ์๊ณ (Blocking ๋์ง ์๊ณ ) ๊ณ์ ์ฝ๋๋ฅผ ์คํํด ๋๊ฐ๋ ๊ฒ์ด๋ค.

๋น๋๊ธฐ ์ฒ๋ฆฌ๋ ๋ฉํฐ์ค๋ ๋๋ฅผ ํตํด์ ํ ์ ์๋ค.
์๋ฐ์์๋ Future Class๋ฅผ ํตํด์ ๋น๋๊ธฐ ์ฒ๋ฆฌ๋ฅผ ํ ์ ์๊ณ Java 8 ๋ฒ์ ์ดํ๋ก๋ CompletableFuture Class๋ฅผ ํตํด์ ๋น๋๊ธฐ ์ฒ๋ฆฌ๋ฅผ ํ ์ ์๊ฒ ๋์๋ค.
์ฃผ์ ๋ฉ์๋
Method | Parameter Type | Return | Description |
---|---|---|---|
runAsync | Runnable, (Option) Executor | CompletableFuture | Task๋ฅผ ๋ฐ์์ ์คํํ๊ณ ๋ฐํํ๋ค. |
supplyAsync | Supplier, (Option) Executor | CompletableFuture | Lambda๋ฅผ ๋ฐ์์ ๋ฆฌํดํ์ (U)์ ๋ฐํํ๋ค. |
allOf | CompletableFuture<?> ... | CompletableFuture | CompletableFuture ๋ฆฌ์คํธ๋ฅผ ๋ฐ์์ ํ๋๋ก ๋ฐํํ๋ค. |
anyOf | CompletableFuture<?> ... | CompletableFuture | CompletableFuture ๋ฆฌ์คํธ๋ฅผ ๋ฐ์์ ํ๋๋ก ๋ฐํํ๋ค. |
Executor executor = Excutors.newFixedThreadPool(2);
CompletableFuture.runAsync(() -> {
try {
Thread.sleep(10L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ": hi");
}, executor);
Executor executor = Excutors.newFixedThreadPool(2);
CompletableFuture.runAsync(() -> {
try {
Thread.sleep(10L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return Thread.currentThread().getName() + ": hi";
}, executor);
allOf์ anyOf๋ CompletableFuture๋ค์ ํ๋๋ก ๋ฌถ์ด์ฃผ๊ณ allOf๋ ๋ชจ๋ ์ข ๋ฃํ ๋๊น์ง, anyOf๋ ์ ์ผ ๋จผ์ ์ข ๋ฃ๋ ํ๋๋ฅผ ๋ฐํํ๋ค.