วิธีการ sleep() เป็น คงที่ วิธีการ กระทู้ คลาสและสามารถส่งเธรดที่กำลังทำงานอยู่ในสถานะ "Non-Runnable" ได้ ในขณะที่รอ() เมธอดเป็นเมธอดอินสแตนซ์ เรากำลังเรียกมันโดยใช้เธรดอ็อบเจ็กต์ และจะมีผลกับอ็อบเจกต์นั้นเท่านั้น นอนหลับ() เมธอด wakeup หลังจากหมดเวลาหรือเรียก interrupt() เมธอด ในขณะที่ รอ() เมธอด wakeup หลังจากหมดเวลาหรือโทร notify() หรือ notifyAll() กระบวนการ. นอนหลับ() เมธอดไม่ปล่อยล็อกหรือตรวจสอบ r ขณะรอ ในขณะที่ รอ() เมธอดจะปลดล็อคหรือมอนิเตอร์ขณะรอ
Syntax for sleep() method
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