public class HelloWorld {
static long start;

public static void main(String[] args) throws InterruptedException, ExecutionException {
HelloWorld helloWorld = new HelloWorld();
Future<String> hello;
System.out.println("[" + System.currentTimeMillis() + "]" + "Start!");
hello = helloWorld.getSayHelloAsync();
System.out.println("[" + System.currentTimeMillis() + "]" + "End!");
System.out.println(hello.get());
}

public String sayHello() throws InterruptedException{
System.out.println("[" + System.currentTimeMillis() + "]calling sayHello()");
Thread.sleep(1000);
System.out.println("[" + System.currentTimeMillis() + "]end sayHello()");
return "[" + System.currentTimeMillis() + "]" + "HelloWorld!";
}

public Future<String> getSayHelloAsync(){
CompletableFuture<String> future = new CompletableFuture<>();
new Thread(()-> {
try {
String result = sayHello();
future.complete(result);
} catch (Exception e) {
future.completeExceptionally(e);
}
}).start();
return future;
}
}
[1552891812467]Start!
[1552891812526]End!
[1552891812526]calling sayHello()
[1552891813526]end sayHello()
[1552891813526]HelloWorld!

여기에서 중요한건 "End!"가 프린트 되는 시점입니다. 동기식은 return을 기다리기 때문에 "End!" 프린트 되기전에 sayHello()함수 안의 내용이 먼저 프린트 되는 반면에, 비동기식은 return을 기다리지 않고 "End!"가 먼저 프린트 되고 후에 sayHello()함수 안의 내용이 먼저 프린트되는 것을 보실 수 있습니다.

return을 기다리는 동기식과 return을 기다리지 않고 다음 작업을 계속 진행하는 비동기식의 차이를 알아 봤습니다.



+ Recent posts