zoukankan      html  css  js  c++  java
  • Java模拟耗时任务异步执行

    说明:耗时任务开启单独线程处理,任务线程处理完毕通知主线程

    1、回调接口定义

    public interface ResponseCallBack {
    
        public void printMsg(String msg);
    
    }

    2、模拟耗时任务线程

    public class TestMain {
    
     
    
        public static void main(String[] args){
    
            ExecutorService executorService = Executors.newFixedThreadPool(1);
    
            executorService.submit(new TestThread(new ResponseCallBack() {
    
                @Override
    
                public void printMsg(String msg) {
    
                    System.out.println("print message: " + msg);
    
                }
    
            }));
    
            executorService.shutdown();
    
        }
    
    }
    
     
    
    class TestThread implements Runnable {
    
     
    
        private ResponseCallBack responseCallBack;
    
     
    
        public TestThread(ResponseCallBack responseCallBack) {
    
            this.responseCallBack = responseCallBack;
    
        }
    
     
    
        @Override
    
        public void run() {
    
            try {
    
                System.out.println(Thread.currentThread().getName() + " start execute");
    
                Thread.sleep(3000);   // 耗时任务
    
                System.out.println(Thread.currentThread().getName() + " end execute");
    
                this.responseCallBack.printMsg("Hello Call Back");  // 耗时任务执行完后,通知主线程
    
            } catch (InterruptedException e) {
    
                e.printStackTrace();
    
            }
    
        }
    
    }
  • 相关阅读:
    c++ ::和:
    c++ extern
    c++ cpp和hpp
    c++ include
    caffe调试
    caffe blob理解
    poj3126
    FFmpeg滤镜使用指南
    Android之Activity之间传递对象
    Server Tomcat v8.0 Server at localhost failed to start.
  • 原文地址:https://www.cnblogs.com/dand/p/10470166.html
Copyright © 2011-2022 走看看