Java - Runnable과 Callable의 차이점 이해하기
public interface Runnable {
public abstract void run();
}
import java.time.LocalTime;
public class RunnableExample1 {
static class MyRunnable implements Runnable {
@Override
public void run() {
String result = "Called at " + LocalTime.now();
System.out.println(result);
}
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
public class RunnableExample2 {
public static void main(String[] args) {
Thread thread = new Thread(
() -> System.out.println("Runnable at " + LocalTime.now()));
thread.start();
}
}
public interface Callable<V> {
V call() throws Exception;
}
import java.time.LocalTime;
import java.util.concurrent.*;
public class CallableExample1 {
static class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
String result = "Called at " + LocalTime.now();
return result;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable callable = new MyCallable();
FutureTask futureTask = new FutureTask(callable);
Thread thread = new Thread(futureTask);
thread.start();
// 결과가 리턴되기를 기다립니다.
System.out.println("result : " + futureTask.get());
}
}
import java.time.LocalTime;
import java.util.concurrent.*;
public class CallableExample2 {
static class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
String result = "Called at " + LocalTime.now();
return result;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(callable); // Runnable일때는 execute메서드
// 결과가 리턴되기를 기다립니다.
System.out.println("result : " + future.get());
}
}