เมื่อเราเรียก start() เมธอดบนเธรด มันทำให้เธรดเริ่มดำเนินการและ run() เมธอดของเธรดถูกเรียกโดย Java Virtual Machine(JVM) . หากเราเรียก run() . โดยตรง วิธีการก็จะถือว่า ปกติ วิธีการแทนที่ ของคลาสเธรด (หรืออินเตอร์เฟสที่รันได้) และมันจะถูกดำเนินการภายในบริบทของเธรดปัจจุบัน ไม่ใช่ในเธรดใหม่
ตัวอย่าง
public class CallRunMethodTest extends Thread {
@Override
public void run() {
System.out.println("In the run() method: " + Thread.currentThread().getName());
for(int i = 0; i < 5 ; i++) {
System.out.println("i: " + i);
try {
Thread.sleep(300);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
public static void main(String[] args) {
CallRunMethodTest t1 = new CallRunMethodTest();
CallRunMethodTest t2 = new CallRunMethodTest();
t1.run(); // calling run() method directly instead of start() method
t2.run(); // calling run() method directly instead of start() method
}
} ในตัวอย่างข้างต้น มีการสร้างสองเธรดและเรียกใช้เมธอด run() บนเธรดโดยตรง แทนที่จะเรียกใช้เมธอด start()
ผลลัพธ์
In the run() method: main i: 0 i: 1 i: 2 i: 3 i: 4 In the run() method: main i: 0 i: 1 i: 2 i: 3 i: 4