面试常问问题——多线程,如何给run方法传参,如何实现线程的返回值

如何给run方法传参?

(1)构造函数传参
(2) 成员变量传参
(3) 回调函数传参

如何实现处理线程的返回值?

(1)主线程等待法

public class CycleWait implements Runnable{
    private  String value;
    @Override
    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 cycleWait=new CycleWait();
        //给方法附上多线程的属性。
        Thread thread =new Thread(cycleWait);
        thread.start();
        //cycleWait.value主线程执行到这里的时候有可能子线程还没有获取到值,所以需要在值为空的时候,让主线程等待。
        int i=0;
        while (cycleWait.value==null){
            //主线程等待法
		        Thread.currentThread().sleep(100);
		         i++;
           		 System.out.println(i);
        }
        System.out.println("value="+cycleWait.value);
    }
}

运行发现需要循环50次即主线程等待50个100毫秒才能取到值,而如果最后一次主线程取到值了,但是主线程还在等待,会有资源占用等其他问题。

(2)使用Thread类的join()方法,阻塞当前线程以等待子线程处理完毕

 public static void main(String[] args) throws InterruptedException {
        CycleWait cycleWait=new CycleWait();
        Thread thread =new Thread(cycleWait);
        thread.start();
        int i=0;
        //join阻塞法
        thread.join();
        System.out.println("value="+cycleWait.value);
    }

通过callable接口实现:通过FutureTask 或者线程池获取

需要jdk是1.5以上。

public class MyCallable implements Callable {
    @Override
    public Object call() throws Exception {
        String value ="test";
        System.out.println("work ready to work");
        Thread.currentThread().sleep(5000);
        System.out.println("task done");
        return value;
    }
    }

调用时

   public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask  futureTask= new FutureTask(new MyCallable());
        new Thread(futureTask).start();
        if(!futureTask.isDone()){
            System.out.println("FutureTask is not done ,please wait!");
        }
        System.out.println("value = "+futureTask.get());
    }

线程池:

public class ThreadPoolDemo {
    public static void main(String[] args) {
       //线程池提交 mycallable的任务。
        ExecutorService executorService = Executors.newCachedThreadPool();
        //向线程池提交
        Future future = executorService.submit(new MyCallable());
        Future future1 =executorService.submit(new MyCallable());
        if(!future.isDone()){
            System.out.println("task has not finished,please wait");
        }
        try {
            System.out.println("value ="+future.get());
            System.out.println("value ="+future1.get());


        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally {
            //结束线程池
            executorService.shutdown();
        }
    }
}

你可能感兴趣的:(多线程,常见问题)