Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เมื่อไหร่ควรเรียก Thread.run() แทน Thread.start() ใน Java


เมื่อเรียก start() บนเธรด จะทำให้เธรดเริ่มทำงานและ run() จะถูกเรียกโดย JVM หากเรียก run() โดยตรง จะถูกจัดเป็น เมธอด override ทั่วไป ของคลาสเธรด (หรือ runnable interface) และทำงานใน บริบทของเธรดปัจจุบัน ไม่ใช่เธรดใหม่

ตัวอย่าง

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
    }
}

ในตัวอย่าง สร้างเธรด 2 ตัว และเรียก 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