如何实现主线程打印子线程的结果(阿里一面)

1.自定义runnable接口实现类

public class MySyncThreadTest {
    public static void main(String[] args) throws Exception {
        CustomRunnable cRunnacle = new CustomRunnable();
        Thread thread = new Thread(cRunnacle,"子线程");
        thread.start(); //子线程执行
        System.out.println("主线程做自己的事情");
        thread.join(); //等待子线程执行完毕,这里会阻塞 
        System.out.println("获取子线程返回结果:"+cRunnacle.getData());
    }
    static final class CustomRunnable implements Runnable{
        private String a = "";
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName()+":执行 start");
                Thread.sleep(2000); //子线程停留2秒
                System.out.println(Thread.currentThread().getName()+":执行 end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            a = "Hello world";
        }
        private String getData() {
            return a;
        }
    }
}

runnable接口的run方法是没有返回值的,因此可以自定义一个方法返回run方法运行的结果

2.Future实现类+Callable

package com.jgyang.com;
 
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
 
public class MySyncThreadTest2 {
 
    public static void main(String[] args) throws Exception {
        CustomCallable cRunnacle = new CustomCallable();
        FutureTask<String> futureTask = new FutureTask<String>(cRunnacle);
        Thread thread = new Thread(futureTask,"子线程");
        thread.start(); //子线程执行
        
        System.out.println("主线程做自己的事情--start");
        System.out.println("获取子线程返回结果:"+futureTask.get());//获取返回结果是会阻塞
        System.out.println("主线程做自己的事情--end");
        
    }
    
    static final class CustomCallable implements Callable<String>{
        public String call() throws Exception {
            System.out.println(Thread.currentThread().getName()+":执行 start");
            Thread.sleep(2000); //子线程停留2秒
            System.out.println(Thread.currentThread().getName()+":执行 end");
            return "Hello world";
        }
        
    }
}
posted @ 2023-03-19 11:02  刚刚好。  阅读(77)  评论(0编辑  收藏  举报