wait()
- เป็นเมธอดของคลาส Object
- ปล่อย Lock (Monitor) เมื่อเรียกใน synchronized block
- ไม่ใช่ static method
- ต้องเรียกจาก synchronized context เท่านั้น (จะได้ IllegalMonitorStateException)
- มี 3 overload:
wait(),wait(long timeout),wait(long timeout, int nanos)
sleep()
- เป็นเมธอด static ของคลาส Thread
- ไม่ปล่อย Lock (ยังคงครอง monitor)
- เป็น static method
- ไม่ต้องอยู่ใน synchronized context
- มี 2 overload:
sleep(long millis),sleep(long millis, int nanos) - InterruptedException ต้อง catch
สรุป
| คุณสมบัติ | wait() | sleep() |
|---|---|---|
| คลาส | Object | Thread |
| ปล่อย Lock | ใช่ | ไม่ |
| Static | ไม่ | ใช่ |
| Context | ต้อง synchronized | ไม่จำเป็น |
| วัตถุประสงค์ | Inter-thread communication | หน่วงเวลา (pause execution) |