獲取線程返回值的方式

(1)主線程等待法

package com.interview.thread;

//獲取多線程返回值1:主線程等待
public class CycleWait implements Runnable{
	private String value;

	@Override
	public void run() {
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.value = "we have data now";
	}
	public static void main(String[] args) throws InterruptedException {
		CycleWait cw = new CycleWait();
		Thread t1 = new Thread(cw);
		t1.start();
		while(cw.value == null) {
				Thread.sleep(100);
		}
		System.out.println("value:" + cw.value);
	}

}

(2)使用Thread的join阻塞當前線程等待

package com.interview.thread;

//獲取多線程返回值1:主線程等待
public class CycleWait implements Runnable{
	private String value;

	@Override
	public void run() {
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.value = "we have data now";
	}
	public static void main(String[] args) throws InterruptedException {
		CycleWait cw = new CycleWait();
		Thread t1 = new Thread(cw);
		t1.start();
		t1.join();
		System.out.println("value:" + cw.value);
	}

}

(3)通過Callable的FutureTask

package com.interview.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;



public class FutureTaskDemo {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		FutureTask<String> task = new FutureTask<>(new MyCallable());
		new Thread(task).start();
		if(!task.isDone()) {
			System.out.println("任務未處理完成。。");
		}
		System.out.println("任務執行結果:" + task.get());
	}
}
class MyCallable implements Callable<String>{

	@Override
	public String call() throws Exception {
		
		String value = "result value";
		System.out.println("線程開始處理任務");
		Thread.sleep(5000);
		System.out.println("線程結束處理任務");
		return value;
	}

}

(4)通過Callable接口,線程池的Future實現

package com.interview.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;



public class FutureTaskDemo {
	public static void main(String[] args) throws Exception {
		ExecutorService pool = Executors.newCachedThreadPool();
		Future<String> future = pool.submit(new MyCallable());
		if(!future.isDone()) {
			System.out.println("等待任務...");
		}
		System.out.println("結果:" + future.get());
		pool.shutdown();
	}
}

class MyCallable implements Callable<String>{

	@Override
	public String call() throws Exception {
		
		String value = "result value";
		System.out.println("線程開始處理任務");
		Thread.sleep(5000);
		System.out.println("線程結束處理任務");
		return value;
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章