学习笔记14 - 给线程传参和处理线程的返回值

传参
class MyThread1 extends Thread{
  /** 2.通过变量和方法传递数据 */
  @Setter
  private String name;

  /** 1.通过构造方法传递数据 */
  public MyThread1(String name) {
      this.name = name;
  }

  /** 3.使用回调函数 */
  public void process(String name){
      this.name = name;
  }

  @Override
  public void run() {
      System.out.println(name);
  }
}
处理返回值
/**
 * 线程
 */
class CycleWait implements Runnable{
    public String value;
    @Override
    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        value = "we have date now";
    }
}
主线程等待法
 CycleWait cw = new CycleWait();
 Thread t = new Thread(cw);
 t.start();
 while (cw.value == null){
     Thread.sleep(100);
 }
 System.out.println("value :" + cw.value);
  • 缺点:如果代码多,代码会臃肿,控制不精准
使用Thread类的join()阻塞当前线程以等待子线程处理完毕
CycleWait cw = new CycleWait();
Thread t = new Thread(cw);
t.start();
t.join();
System.out.println("value :" + cw.value);
  • 缺点:力度不够
通过Callable接口实现:通过FutureTask Or 线程池获取
class MyCallable implements Callable<String>{
    @Override
    public String call() throws Exception {
        String value = "test";
        System.out.println("Ready to word");
        Thread.sleep(5000);
        System.out.println("task dene");
        return value;
    }
}
Future方式
FutureTask<String> task = new FutureTask<>(new MyCallable());
new Thread(task).start();
if (!task.isDone()){
    System.out.println("正在等待。。。");
  }
System.out.println(task.get());
线程池
 ExecutorService newCachedThreadPoll = Executors.newCachedThreadPool();
 Future<String> future = newCachedThreadPoll.submit(new MyCallable());
 if (!future.isDone()){
     System.out.println("正在等待。。。");
 }
 try {
     System.out.println(future.get());
 } catch (InterruptedException e) {
     e.printStackTrace();
 } catch (ExecutionException e) {
     e.printStackTrace();
 }finally {
     newCachedThreadPoll.shutdown();
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值