1、run()
Thread的run()方法来自于Runnable接口,Thread的子类应该重写该方法,调用run()方法,只是相当于调用一个类中的一个普通方法,会在本线程中执行run()的方法体,不会开启另外一个线程!
2、start()
执行Thread的start()方法,会开启一个新的线程,在新的线程里面执行run()方法。
(If you directly call run() method, you are not using multi-threading feature since run() method is executed as part of caller thread.
If you call start() method on Thread, the Java Virtual Machine will call run() method and two threads will run concurrently - Current Thread (main() in your example) and Other Thread (Runnable r1 in your example).)
Example
public class PingPong {
public static synchronized void main(String args[]) {
Thread t = new Thread() {
public void run() {
pong();
}
};
t.start();
System.out.print("Ping");
}
static synchronized void pong() {
System.out.print("Pong");
}
}
输出:PingPong。因为主线程先获取到PingPong.class的管程锁,所以线程t必须等待主线程结束释放锁,才能执行pong()方法。
public class PingPong {
public static synchronized void main(String args[]) {
Thread t = new Thread() {
public void run() {
pong();
}
};
//t.start();
t.run();
System.out.print("Ping");
}
static synchronized void pong() {
System.out.print("Pong");
}
}
输出:PongPing。执行t的run()方法只是简单的方法调用,直接在主线程执行pong()方法,pong()方法执行完之后顺序执行。
示例以及代码来自于《Java解惑》谜题76-乒乓。