多线程:线程返回值的处理

1. 主线程等待法

run()方法不能返回值。

public class Method1 implements Runnable {
    private String value;

    @Override
    public void run() {
        try{
            Thread.currentThread().sleep(2000);
        } catch(Exception e) {
            e.printStackTrace();
        }
        value = "Now we have value.";
    }

    public static void main(String[] args) throws Exception {
        Method1 m1 = new Method1();
        Thread t1 = new Thread(m1);

        t1.start();

        while(m1.value == null) {//如果值为null,等待0.1s
            Thread.currentThread().sleep(100);
        }

        System.out.println(m1.value);
    }
}

2. join()

join():确保调用该方法的线程执行完毕之后再继续向下执行代码

public class Method2 implements Runnable {
    private String value;

    @Override
    public void run() {
        try{
            Thread.currentThread().sleep(2000);
        } catch(Exception e) {
            e.printStackTrace();
        }
        value = "Now we have value.";
    }

    public static void main(String[] args) throws Exception {
        Method2 m2 = new Method2();
        Thread t1 = new Thread(m2);

        t1.start();

        t1.join();

        System.out.println(m2.value);
    }
}

3. Callable()

实现Callable()接口需要重写call()方法,而该方法具有返回值(默认返回Object)
可以通过FutureTaskget()方法获取call()的返回值

3.1. FutureTask

class Method3 implements Callable {
    @Override
    public String call() throws Exception {
        System.out.println("Ready");
        Thread.currentThread().sleep(2000);
        String str = "Message Get!";
        System.out.println("Finish");
        return str;
    }
}

class Test {
    public static void main(String[] args) throws Exception {
        Method3 m3 = new Method3();
        FutureTask ft = new FutureTask(m3);
        Thread t1 = new Thread(ft);
        t1.start();

        if(!ft.isDone()) {
            System.out.println("Task preparing..");
        }

        System.out.println(ft.get());//获取call方法返回值
    }
}

3.2. 线程池

public class Method4  {
    public static void main(String[] args) {
        ExecutorService es = Executors.newCachedThreadPool();
        Future future = es.submit(new Method3());

        if(!future.isDone()) {
            System.out.println("Task preparing..");
        }

        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            es.shutdown();
        }
    }
}

你可能感兴趣的:(要点,java)