创建线程的几种方式
1、继承Thread类,重写run方法
class MyThread extends Thread{
@Override
public void run() {
super.run();
}
}
public class TestThreadCreat {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.run();
}
}
2、实现Runnable接口
匿名内部类(参数处之间用new Runnable)
lamdba表达式(()->{})
class MyThread implements Runnable{
@Override
public void run() {
System.out.println("mythread2 run ");
}
}
public class TestThreadCreat {
public static void main(String[] args) {
(1)、MyThread myThread = new MyThread();
myThread2.run();
(2)、Thread thread = new Thread(new MyThread2(),"A");
thread.run();
(3)、Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
}
}, "B");
(4)、Thread thread2 = new Thread(() -> {
}, "C");
}
}
//1 class MyThread implements Runnable
//2 匿名内部类
//3 laExpress
3、实现Callable接口,重写call方法
与实现runnable接口的不同之处:
- 方法不同,一个是Runnable一个是Callable
- Runnable中的run方法不抛异常,Callable中的call方法会抛异常
- Runnable中的run方法没有返回值,Callable中的call方法有返回值
- Callable接口带了泛型,而Runnable没有泛型
调用的时候需要借助FutureTask来进行辅助,一个FutureTask不管有几个线程进行调用,那么也之后执行一次
class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
return null;
}
}
public class TestThreadCreat {
public static void main(String[] args) {
//Thread只能传入实现Runnable接口的东西
//若想传入实现Callable接口的东西,需要找一个Runnable的子类
//FutureTask就是Runnable的子类
//FutureTask的构造方法可以传入一个实现Callable接口的参数
//这样就可以实现Thread的构造
FutureTask task = new FutureTask(new MyThread());
Thread thread = new Thread(task, "c");
thread3.start();
//task.get()获取Callable中的call方法的返回值
System.out.println(task.get());
}
}