Java
자바 Callback
NaHyungMin
2020. 11. 3. 17:39
package main.java.com;
public class CallbackMain {
public static void main(String args[]) {
System.out.println("start");
MyCallback callback = new MyCallback();
//성공 케이스.
callback.doWork("4", "7");
//실패 케이스.
callback.doWork("4", "&");
callback.finish();
System.out.println("end");
}
}
package main.java.com;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyCallback {
private ExecutorService executorService;
public MyCallback(){
this.executorService = Executors.newCachedThreadPool();
}
private CompletionHandler<Integer, Void> callback = new CompletionHandler<Integer, Void>() {
@Override
public void completed(Integer result, Void attachment) {
System.out.println("Completed");
}
@Override
public void failed(Throwable exc, Void attachment) {
System.out.println("Failed");
}
};
public void doWork(final String x, final String y){
Runnable task = new Runnable() {
@Override
public void run() {
try{
int result = Integer.parseInt(x) + Integer.parseInt(y);
callback.completed(result, null);
}catch (Exception ex){
callback.failed(ex,null);
}
}
};
executorService.submit(task);
}
public void finish(){
executorService.shutdown();
}
}