一个简单的异步回调java实现

从刚接触jquery时感受到了回调这种写法,之后学习android的时候,发现也提供了很多回调方法.于是一直自己想写一写 回调.最近在学习netty.于是开始实现了一下.
代码:

public class Task2 implements Runnable {
    private Callbacka callbacka;

    public Task2(Callbacka callbacka) {
        this.callbacka = callbacka;
    }

    @Override
    public void run() {
        try {
            callbacka.func();

            callbacka.onSuccess();
        }catch (Exception e){
            callbacka.onFailure(e);
        }

    }
}

public interface Callbacka {
    public void func();
    public void onSuccess();
    public void onFailure(Exception e);
}
public class Testtt {
    public static void main(String[] args){
        MyThreadPool myThreadPool=new MyThreadPool();
//        Task task1=new Task(new Callbacka() {
//            @Override
//            public void func() {
//                System.out.println(Thread.currentThread().getName()+"  假装在做些什么");
//                try {
//                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println(Thread.currentThread().getName()+" 做完了");
//            }
//            @Override
//            public void onSuccess() {
//                System.out.println(Thread.currentThread().getName()+" 做完了之后要这样做,请注意看看");
//            }
//        });
        Task2 task1=new Task2(new Callbacka() {
            @Override
            public void func() {
                System.out.println(Thread.currentThread().getName()+"  假装在做些什么");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+" 做完了");
            }

            @Override
            public void onSuccess() {
                System.out.println(Thread.currentThread().getName()+" 做完了之后要这样做,请注意看看");
            }

            @Override
            public void onFailure(Exception e) {
                System.out.println(Thread.currentThread().getName()+" 出现了异常");
            }
        });
        ExecutorService executorService= Executors.newCachedThreadPool();
        executorService.submit(task1);
        System.out.println(Thread.currentThread().getName()+" 我在主线程啊!没被阻塞啊");
        System.out.println(Thread.currentThread().getName()+" 主线程在做写工作");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+" 主线程做完了");
    }
}

你可能感兴趣的:(一个简单的异步回调java实现)