如何创建线程?
创建线程主要有两种方式继承Thread类、实现Runable接口两种方式。
通过查看Thread类的构造方法可知
继承Thread类
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("This's my thread implement. name = " + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread a = new MyThread();
Thread b = new MyThread();
a.start();
b.start();
}
}
实现Runable接口
public class MyRunable implements Runnable {
@Override
public void run() {
System.out.println("This's my Runable implement. name = " + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread a = new Thread(new MyRunable());
Thread b = new Thread(new MyRunable());
a.start();
b.start();
}
}
使用lambda表达式简化写法
对此种写法有疑问的同学可以取看看“函数式接口”的定义。
public class MyLambdaDemo {
public static void main(String[] args) {
// 方式A
Runnable runnable = () -> System.out.println("lambda to create a new thread. A");
Thread a = new Thread(runnable);
// 方式B
Thread b = new Thread(() -> System.out.println("lambda to create a new thread. B"));
a.start();
b.start();
// out
// lambda to create a new thread. A
// lambda to create a new thread. B
}
}
run方法和start方法的差异
在上面我们创建一个Thread类的实例后,是调用start方法来启动线程的,与此同时还有run方法也可启动类。那么二者的差别在哪里呢?
先上结论:run方法启动线程不会创建一个新的线程,只会在当前线程执行Thread类的run方法体,换而言之,run方法启动会串行的执行,就失去了创建一个Thread类的意义;而start会新开启一个线程
public class RunOrStart {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
Thread a = new Thread(() -> System.out.println(Thread.currentThread().getName()));
a.start();
Thread b = new Thread(() -> System.out.println(Thread.currentThread().getName()));
b.run();
// out
// main
// Thread-0
// main
}
}