java 5.0新线程的写法

package tarena;
//5.0新线程的写法
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

public class TestExecutors implements Callable {
	private int state = 0;
	public TestExecutors(int state) {
		this.state = state;
	}
	public String call() throws Exception {
		if (state == 0) {
			return "ok";
		} else if (state == 1) {
			while (true) {
				System.out.print("superman");
				Thread.sleep(100);
			}
		} else if (state == -1) {
			throw new Exception("error");
		}
		return null;
	}
	public static void main(String[] args) {
		ExecutorService e = Executors.newFixedThreadPool(3);
		Future f1 = e.submit(new TestExecutors(0));
		Future f2 = e.submit(new TestExecutors(1));
		Future f3 = e.submit(new TestExecutors(-1));
		try {
			System.out.println(f1.get());
			System.out.println(f2.cancel(true));
			System.out.println(f3.get());
		} catch (Exception ee) {
			ee.printStackTrace();
		}
		e.shutdown();// 当用public static void main(String[] args) throws
		// Exception时 不能结束
	}  
}

 

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