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();
            }
        }
    }
    

      

  • 相关阅读:
    【开源】知乎日报UWP 更新
    【开源】知乎日报UWP 更新
    耿丹学院软工助教(2016年上半年)
    c++ STL map 结构体
    2016搜狐笔试二叉树和最大的子树
    从B树、B+树、B*树谈到R 树
    C++继承:公有,私有,保护
    循环队列
    C++中的static关键字
    c++map的用法
  • 原文地址:https://www.cnblogs.com/vingLiu/p/10663385.html
Copyright © 2011-2022 走看看