在Java创建一个线程的时候, 通常是有两种方法, 一种是重写run()方法, 调用对象实例的start()方法; 一种是实现Runnable接口, 重写run()方法, 将对象实例作为Thread类初始化方法的实参, 并调用新生成的Thread类实例的start()方法.
older syntax:
public class MyThread extends Thread {
public void run() {
// your code here
}
}
MyThread myThread = new MyThread();
myTread.start();
或者:
Thread thread = new Thread() {
public void run() {
// your code here
}
}
thread.start();
lambda:
new Thread(() -> /* your code here*/ ).start();
older syntax:
// pre java 8 lambdas
Thread t = new Thread(new Runnable() {
public void run() {
// your code here ...
}
});
t.start();
lambda:
Runnable runnable = () -> {
// your code here ...
};
Thread t = new Thread(runnable);
t.start();
实现Runnable接口相较于继承Thread的优势: