线程中run方法和start方法的区别
第一个区别
- run方法是普通方法,并不会新创建线程。
- start方法会创建一个新线程去执行。
run方法
public class ThreadDemo12 {
public static class MyThread extends Thread{
@Override
public void run(){
System.out.println("我是线程1"+
Thread.currentThread().getName());
}
}
public static void main(String[] args) {
MyThread thread=new MyThread();
//相当于调用一个类的普通方法而已,并不是创建了新线程执行的
thread.run();
}
}
start方法
public class ThreadDemo12 {
public static class MyThread extends Thread{
@Override
public void run(){
System.out.println("我是线程1"+
Thread.currentThread().getName());
}
}
public static void main(String[] args) {
MyThread thread=new MyThread();
//相当于创建了一个新线程并且执行了run方法
thread.start();
}
}
第二种区别
- run方法可以多次调用
- start方法不可以多次调用
run方法
public class ThreadDemo12 {
public static class MyThread extends Thread{
@Override
public void run(){
System.out.println("我是线程1"+
Thread.currentThread().getName());
}
}
public static void main(String[] args) {
MyThread thread=new MyThread();
//相当于创建了一个新线程并且执行了run方法
//thread.start();
//相当于调用一个类的普通方法而已,并不是创建了新线程执行的
thread.run();
thread.run();
}
}
start方法
public class ThreadDemo12 {
public static class MyThread extends Thread{
@Override
public void run(){
System.out.println("我是线程1"+
Thread.currentThread().getName());
}
}
public static void main(String[] args) {
MyThread thread=new MyThread();
//相当于创建了一个新线程并且执行了run方法
thread.start();
thread.start();
}
}
第三种区别
- run方法属于自定义的实现类
- start方法属于 Thread 类
(经典面试题)