三种创建方式
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口
继承Thread类
- 定义类继承Thread。
- 重写run()方法,编写线程执行体。
- 创建线程对象,调用start()方法启动线程。
实现Runnable接口
- 定义类实现Runnable接口。
- 重写run()方法,编写线程执行体。
- 创建线程对象,将自己作为参数传入,调用start()方法启动线程。
package com.liu.end;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @author liucong
* @date 2020/9/21 - 18:06
*/
//回顾总结线程的创建
public class ThreadEnd {
public static void main(String[] args) {
new MyThread1().start();
new Thread(new MyThread2()).start();
FutureTask<Integer> futureTask=new FutureTask<>(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();
}
}
}
//1.继承Thread类
class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("MyThread1");
}
}
//2.实现Runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("MyThread2");
}
}
//3.实现Callable接口
class MyThread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("MyThread3");
return 10;
}
}