run()方法与start()方法有什么区别?
通常,系统通过调用线程类的start()方法来启动一个线程、此时该线程处于就绪状态,等待调度,即就是这个线程可以被JVM来调度执行。在调度过程中,JVM底层通过调用线程类的run()方法来完成实际的操作,当run()方法结束后,此线程就会终止。
如果直接调用线程类的run()方法,此时run()方法仅仅被当做一个普通的函数调用,程序中仍然只有主线程这一个线程
start()方法能够异步的调用run()方法,但是直接调用run()方法却是同步的。
class MyThread implements Runnable{
@Override
public void run() {
for(int i = 0;i < 10;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread thread = new MyThread();
new Thread(thread,"A").start();
new Thread(thread,"B").start();
}
}

class MyThread implements Runnable{
@Override
public void run() {
for(int i = 0;i < 10;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread thread = new MyThread();
thread.run();
thread.run();
}
}

通俗的来讲run()方法的怎么执行取决于调度者是谁、如果是JVM调度的run()方法,那么此时就是异步处理,如果是直接调用run()方法,那么就和普通函数没有什么区别。
博客主要探讨线程类中run()方法与start()方法的区别。调用start()方法会启动线程,使其处于就绪状态,由JVM调度执行run()方法完成实际操作;若直接调用run()方法,它仅作为普通函数,程序只有主线程。start()异步调用run(),直接调用run()则是同步的。

1350

被折叠的 条评论
为什么被折叠?



