主线程等待10秒钟,无应答返回(二)

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.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Demo2ThreadMain {

	public static void main(String[] args) {
		ExecutorService pool = Executors.newFixedThreadPool(2);
		long mainThreadWaitTime = 3000;
		System.out.println("我是主线程,我最多等待子线程" + (mainThreadWaitTime / 1000)+ "秒钟");
		Future<Integer> result = pool.submit(new SubThread(5000));
		pool.shutdown();
		try {
			Integer resultInt = result.get(mainThreadWaitTime, TimeUnit.MILLISECONDS);
			System.out.println("我是主线程,我等到子线程结束,拿到执行结果:" + resultInt);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			// e.printStackTrace();
			System.out.println("我是主线程,我没有等到子线程结束,超时了");
		}
	}
}
class SubThread implements Callable<Integer> {

	private long time;
	public SubThread(long time) {
		this.time = time;
	}
	public Integer call() throws Exception {
		System.out.println("我是子线程.我要消耗" + (time / 1000) + "秒钟");
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("我是子线程.执行完毕");
		return 1;
	}

}

 

 

你可能感兴趣的:(线程)