先从一个简单的程序看起:
使用start():
public class ThreadTest {
private static void attack(){
System.out.println("fight");
System.out.println("current thread is:" + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
attack();
}
};
System.out.println("current main thread is:" + Thread.currentThread().getName());
thread.start();
}
}
可以看出线程被切换了不是主线程去执行非main的方法。
使用run()方法:
public class ThreadTest {
private static void attack(){
System.out.println("fight");
System.out.println("current thread is:" + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
attack();
}
};
System.out.println("current main thread is:" + Thread.currentThread().getName());
thread.run();
}
}
输出结果为:
从结果可以看出不管是主线程还是其他的线程方法,在run方法下执行的线程都是用主线程去执行。
原理如下:
- 调用start()方法会创建一个新的子线程并启动;
- run()方法只是Thread的一个普通方法的调用。