首页 > 其他 > 详细

如何给run()方法传参数

时间:2019-04-06 23:27:27      阅读:954      评论:0      收藏:0      [点我收藏+]

实现的方式主要有三种

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

  

 

如何给run()方法传参数

原文:https://www.cnblogs.com/vingLiu/p/10663385.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!