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

ความแตกต่างระหว่าง wait() และ sleep() ใน Java


sleep() เป็น static method ของคลาส Thread ทำให้เธรดปัจจุบันเข้าสู่สถานะ "Non-Runnable" ส่วน wait() เป็น instance method เรียกผ่านออบเจ็กต์เธรด และมีผลต่อออบเจ็กต์นั้นอย่างเดียว sleep() จะปลุกตัวเองเมื่อเวลาหมดหรือถูก interrupt() ส่วน wait() จะปลุกเมื่อเวลาหมดหรือถูก notify() หรือ notifyAll() sleep() ไม่ปล่อย lock/monitor ขณะรอ ส่วน wait() ปล่อย lock/monitor ขณะรอ

ไวยากรณ์ sleep()

public static void sleep(long millis) throws InterruptedException

ไวยากรณ์ wait()

public final void wait() throws InterruptedException

ตัวอย่าง

public class ThreadTest implements Runnable {
    private int number = 10;

    public void methodOne() throws Exception {
        synchronized(this) {
            number += 50;
            System.out.println("Number in methodOne(): " + number);
        }
    }

    public void methodTwo() throws Exception {
        synchronized(this) {
            Thread.sleep(2000); // calling sleep() method
            this.wait(1000); // calling wait() method
            number *= 75;
            System.out.println("Number in methodTwo(): " + number);
        }
    }

    public void run() {
        try {
            methodOne();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        ThreadTest threadTest = new ThreadTest();
        Thread thread = new Thread(threadTest);
        thread.start();
        threadTest.methodTwo();
    }
}

ผลลัพธ์

Number in methodOne(): 60 Number in methodTwo(): 4500