클린코드에서 동시성 파트를 읽었는데 내용 자체가 어렵고 클린코드에서 Concurrent패키지와 Executors를 활용하라고 했는데 뭔지 몰라서 그런게 있구나 하고 넘어갔다. 근데 갑자기 기선님 강의 Concurrent를 들을 차례가 나와서 집중해서 들었다.
자바에서는 멀티 프로세싱과 멀티 쓰레드 Concurrent 프로그래밍을 지원한다.
public class Main {
public static void main(String[] args) throws IOException {
MyThread myThread = new MyThread();
myThread.start();
System.out.println("Hello");
//Hello와 1의 출력순서를 보장할 수 없다.
}
}
class MyThread extends Thread{
@Override
public void run() {
System.out.println("1");
}
}
위와 같이 Thread클래스를 상속받고 run메서드를 재정의 하여 Thread를 실행시키는 방법이 있다.
public class Main{
public static void main(String[] args) throws IOException {
Thread thread = new Thread(()->{
System.out.println("1");
});
thread.start();
System.out.println("hello");
//Hello와 1의 출력순서를 보장할 수 없다.
}
}
Runnable을 Thread의 파라미터로 넘겨주어 내부 익명함수를 람다를 통해 run을 재정의 하여 사용할 수 있다.
개발자가 Thread의 메서드를 통해 수십,수백개의 멀티 스레드를 저수준에서 직접 관리하기는 사실상 불가능이고 그렇게 하면 안됨
ExecutorService의 내부 동작과정
(글씨체 ㅈㅅ)
비동기적인 작업의 현재 상태를 조회하거나 결과를 가져올 수 있다.
get() : 결과를 가져오기
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<String> hello = ()->{
Thread.sleep(2000L);
return "Hello";
};
Future<String> submit = executorService.submit(hello);
System.out.println("start");
submit.get();//스레드가 종료될때 까지 계속 대기 == 블록킹 콜
System.out.println("end");
bw.flush();
}
isDone() : 작업 상태 확인하기
cancel() : 작업 취소하기
invokeAll() : 여러 작업 동시에 실행하기
invokeAny() : 여러 작업중에 하나라도 먼저 응답이 오면 끝내기
자바에서 비동기 프로그래밍을 가능하게 하는 인터페이스
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("sijun");
});
future.get();
}
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "sijun";
});
System.out.println(future.get());
}
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "sijun";
}).thenApply((s)->{
return s.toUpperCase(Locale.ROOT);
});
System.out.println(future.get());
}
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
return "Sijun";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
return "Love";
});
System.out.println(future1.thenCompose(Main::getLove).get());
}
private static CompletableFuture<String> getLove(String msg){
return CompletableFuture.supplyAsync(() -> {
return msg+"Love";
});
}
thenCombine()
두 작업을 독립적으로 실행하고 둘 다 종료 했을 때 콜백 실행
allOf()
여러 작업을 모두 실행하고 모든 작업 결과에 콜백 실행
anyOf()
여러 작업 중에 가장 빨리 끝난 하나의 결과에 콜백 실행