1.继承Thread方法,并覆写run方法;
private static class MyThread extends Thread{
@Override
public void run() {
System.out.println("继承线程类");
}
}
//创建并启动
MyThread myThread = new MyThread();
myThread.start();
缺点:类的继承是单继承
2.实现Runable接口,作为参数
private static class MyRunable implements Runnable {
@Override
public void run() {
System.out.println("实现Runnable接口");
}
}
//创建接口,创建线程,并将接口作为参数
MyRunable myRunable = new MyRunable();
Thread thread = new Thread(myRunable);
thread.start();
3.将Thread作为参数(因为Thead也实现了Runnable接口)
Thread thread1 = new Thread(myThread);
thread1.start();
λ表达式
//创建内部类
Thread t = new Thread(){
@Override
public void run() {
}
};
//λ表达式
Thread t2 = new Thread(() -> {
});
->的内容可以用AIt+回车键打开内容和上面一样;表示的意思也是实现了Runnable接口,重写了run方法;
run() 和 start()
1.若调用run()方法将不会创建线程,而是直接执行run()方法;
2.调用start将会启动线程,并且会执行run()方法;