public class ThreadSummary {
public static void main(String[] args) {
new MyThread1().start();
new Thread(new MyThread2()).start();
// FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
// new Thread(futureTask).start();
// try {
// Integer integer = futureTask.get();
// System.out.println(integer);
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(1);
//提交执行
Future<Integer> result = ser.submit(new MyThread3());
//获取结果
try {
int r = result.get();
System.out.println(r);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//关闭服务
ser.shutdown();
}
}
//1.继承Thread类
class MyThread1 extends Thread {
@Override
public void run() {
System.out.println("MyThread1");
}
}
//2.实现runnable接口
class MyThread2 implements Runnable {
public void run() {
System.out.println("MyThread2");
}
}
//3.实现Callable接口
class MyThread3 implements Callable<Integer> {
public Integer call() throws Exception {
System.out.println("MyThread3");
return 10;
}
}
多线程创建方式总结
最新推荐文章于 2024-05-31 10:46:10 发布