Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khác biệt giữa wait() và sleep() trong Java?

Phương thức sleep() là phương thức static của lớp Thread đưa luồng hiện tại vào trạng thái "Non-Runnable". Trong khi wait() là phương thức instance, gọi qua đối tượng thread và chỉ ảnh hưởng đến đối tượng đó. sleep() thức dậy sau khi hết thời gian hoặc gọi interrupt(); wait() thức dậy sau khi hết thời gian hoặc gọi notify() / notifyAll(). sleep() không giải phóng khóa (lock/monitor) trong khi chờ, còn wait() giải phóng khóa.

Cú pháp sleep()

public static void sleep(long millis) throws InterruptedException

Cú pháp wait()

public final void wait() throws InterruptedException

Ví dụ

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); // gọi sleep() 
            this.wait(1000); // gọi wait() 
            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(); 
    } 
}

Kết quả

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