zoukankan      html  css  js  c++  java
  • 如何给run()方法传参数

    实现的方式主要有三种

    1、构造函数传参

    2、成员变量传参

    3、回调函数传参

    问题:如何实现处理线程的返回值?

    1、主线程等待法(优点:实现起来简单,缺点:需要等待的变量一多的话,代码就变的非常臃肿。而且不能精准控制时间

    public class CycleWait implements Runnable{
        private String value;
        public void run() {
            try {
                Thread.currentThread().sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            value = "we have data now";
        }
    
        public static void main(String[] args) throws InterruptedException {
            CycleWait cw = new CycleWait();
            Thread t = new Thread(cw);
            t.start();
    //        while (cw.value == null){
    //            Thread.currentThread().sleep(100);
    //        }
            t.join();
            System.out.println("value : " + cw.value);
        }
    }
    

      

    2、使用Thread类的join()阻塞当前线程以等待子线程处理完毕(缺点:精准度不够)

    3、通过Callable接口实现:通过FutureTask Or 线程池获取

    public class MyCallable implements Callable<String> {
        @Override
        public String call() throws Exception{
            String value="test";
            System.out.println("Ready to work");
            Thread.currentThread().sleep(5000);
            System.out.println("task done");
            return  value;
        }
    }
    

    FutureTask 实现方式

    public class FutureTaskDemo {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            FutureTask<String> task = new FutureTask<String>(new MyCallable());
            new Thread(task).start();
            if(!task.isDone()){
                System.out.println("task has not finished, please wait!");
            }
            System.out.println("task return: " + task.get());
        }
    }
    

    线程池实现方式

    public class ThreadPoolDemo {
        public static void main(String[] args) {
            ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
            Future<String> future = newCachedThreadPool.submit(new MyCallable());
            if(!future.isDone()){
                System.out.println("task has not finished, please wait!");
            }
            try {
                System.out.println(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } finally {
                newCachedThreadPool.shutdown();
            }
        }
    }
    

      

  • 相关阅读:
    [ Scala ]关于scala环境搭建过程中,sbt编译中maven下载失败的解决方案(改成阿里的maven仓库)
    复习笔记:一个简单的动态代理实现
    复习笔记:一个简单的反射工厂Demo
    定时器Timer如何终止运行的问题
    Python RESTful接口开发02
    python 内置模块 logging的使用
    Django项目数据处理的流程是怎样的
    Django-Redis:在Django中使用redis作为缓存
    Python RESTful 接口开发01
    teamview
  • 原文地址:https://www.cnblogs.com/vingLiu/p/10663385.html
Copyright © 2011-2022 走看看