首先sleep()和wait()从效果上看,都可以使线程进入阻塞状态
- 不同点:
- Sleep方法是Thread类的静态方法,wait方法是Object超类的成员方法
- wait,notify和notifyAll只能在同步控制方法或者同步控制块里面使用,否则会抛出异常,而sleep可以在任何地方使用
- 本质区别
a. Sleep不会释放同步锁,使得其他线程无法使用同步控制块或者方法
测试:
import java.text.SimpleDateFormat; import java.util.Date; public class TestSleepAndWait { public static void main(String[] args) { SleepThread target = new SleepThread(); Thread t1 = new Thread(target); Thread t2 = new Thread(target); Thread t3 = new Thread(target); t1.start(); t2.start(); t3.start(); } } class SleepThread implements Runnable{ @Override public synchronized void run() { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); System.out.println(Thread.currentThread().getName()+"准备休眠:"+sdf.format(new Date())); Thread.sleep(3000); System.out.println(Thread.currentThread().getName()+"休眠了3秒钟"+sdf.format(new Date())); } catch (InterruptedException e) { e.printStackTrace(); } } }
结果打印如下
b. Wait会释放同步锁,使得其他线程可以使用同步控制块或者方法
测试:
public class TestSleepAndWait { public static void main(String[] args) { TestWait target = new TestWait(); Thread t1 = new Thread(target); Thread t2 = new Thread(target); Thread t3 = new Thread(target); t1.start(); t2.start(); t3.start(); } } class TestWait implements Runnable{ public synchronized void run() { try{ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); System.out.println(Thread.currentThread().getName()+"准备休眠:"+sdf.format(new Date())); this.wait(3000); System.out.println(Thread.currentThread().getName()+"休眠了3秒钟"+sdf.format(new Date())); }catch (InterruptedException e){ e.printStackTrace(); } } }
结果打印:
总的来说,其本质的区别还是在于锁的释放