java利用回调机制实现异步处理实例

异步请求,发起请求后立即返回去执行其它任务,等到请求业务处理完成后,利用回调机制通知发起请求的线程;


这里利用java模拟异步请求文件复制的过程: Test请求FileUtils的callbackAfterCopy方法,FileUtils的callbackAfterCopy方法创建线程执行完复制任务后会调用Test的afterCopy方法【If you call me, i will call you back】通知Test的main线程复制完成

import java.io.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/*
* 回调接口
*/
public interface FileHandleCallable {
    void afterCopy(); //复制完成后的回调事件
}

class Test implements FileHandleCallable{
    static volatile boolean isCompleted = false;
    static CountDownLatch latch=new CountDownLatch(1);

    void requestCopy(FileUtils tool, File source, File dest){
        tool.callbackAfterCopy( this, source,  dest); //If you call me
    }
    /*
    * 实现回调方法,通知请求复制的线程复制完成
    */
    public void afterCopy(){
        isCompleted=true;
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("copying is complete");
    }

    public static void main(String[] args) throws InterruptedException {

        File source=new File("filename.zip");
        File dest=new File("new_filename.zip");

        new Test().requestCopy(new FileUtils(),source,dest); //向FileUtils发起复制请求
        /*
        * 异步请求直接返回,可以处理其它任务
        * 在这里为打印"download..."的任务
        * 执行回调后isCompleted为true,退出循环打印任务
        */
        while(!isCompleted){

            TimeUnit.MILLISECONDS.sleep(1_0);
            if(isCompleted) break;
            System.out.println("download...");
        }
        latch.countDown();
    }
}

class FileUtils{

    public void callbackAfterCopy(FileHandleCallable o,File source, File dest){
        new Thread(()->{
            try {
                copyFileUsingFileStreams(source,dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            o.afterCopy(); //i will call you back; 
        }).start();
    }
    private static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }
}

你可能感兴趣的:(java)