JAVA利用线程池控制方法执行时间

package cn;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author zhangming
 *
 */
public class TestFurther {

	public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(1);
		FutureTask futureTask = new FutureTask<>(
				new Callable() {
					@Override
					public Boolean call() throws Exception {
						System.out.println("不告诉你。");
						Thread.sleep(1000 * 3);
						System.out.println("8888888888");
						return false;
					}
				});
		try {
			executorService.submit(futureTask).get(2, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TimeoutException e) {
			System.out.println("超时了吧~~~");
			e.printStackTrace();
			executorService.shutdownNow();
		}
	}
}

 

你可能感兴趣的:(J2SE)