创建线程有5种方式~下面来一一介绍
1. 继承 Thread,重写run的方式来创建线程
使用 Thread 的 run 描述线程入口
class MyThread extends Thread{
@Override
public void run() {
System.out.println("hello thread");
}
}
// 最基本的创建线程的办法
public class Demo1 {
public static void main(String[] args) {
Thread t = new MyThread();
t.start(); // 会创建新线程
}
}
2 定义一个类,使用实现 Runnable,重写 run
使用 Runnable interface 来描述线程入口
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("hello");
}
}
public class Demo3 {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
3. 继承 Thread,使用匿名内部类
public class Demo4 {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
System.out.println("hello");
}
};
t.start();
}
}
4. 实现Runnable,使用匿名内部类
public class Demo5 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello");
}
} );
t.start();
}
}
5. 使用lambda表达式(最推荐写法)
public class Demo5 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello");
}
} );
t.start();
}
}