多线程23:总结

回顾总结线程的创建:
三种:1.继承Thread类、2.实现Runnable接口、3.实现Callable接口
 1 package com.thread.gaoji;
 2 
 3 import java.util.concurrent.Callable;
 4 import java.util.concurrent.ExecutionException;
 5 import java.util.concurrent.FutureTask;
 6 
 7 //回顾总结线程的创建
 8 public class ThreadNew {
 9     public static void main(String[] args) {
10         new MyThread1().start();
11 
12         new Thread(new MyThread2()).start();
13 
14         //FutureTask实现了一个RunnableFuture接口,RunnableFuture接口继承了Runnable,实现了run方法
15         FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
16         new Thread(futureTask).start();
17 
18         try {
19             Integer integer = futureTask.get();
20             System.out.println(integer);
21         } catch (InterruptedException e) {
22             e.printStackTrace();
23         } catch (ExecutionException e) {
24             e.printStackTrace();
25         }
26 
27     }
28 }
29 
30 
31 //1.继承Thread类
32 class MyThread1 extends Thread {
33     @Override
34     public void run() {
35         System.out.println("MyThread1");
36     }
37 }
38 
39 //2.实现Runnable接口
40 class MyThread2 implements Runnable {
41 
42     @Override
43     public void run() {
44         System.out.println("MyThread2");
45     }
46 }
47 
48 //3.实现Callable接口
49 class MyThread3 implements Callable<Integer> {
50 
51     @Override
52     public Integer call() throws Exception {
53         System.out.println("MyThread3");
54         return 100;
55     }
56 }
57 
58 结果:
59 MyThread1
60 MyThread2
61 MyThread3
62 100
原文地址:https://www.cnblogs.com/duanfu/p/12260826.html