结合synchronized,会更好的理解sleep()和wait()这两个方法,当然也就知道了他们的区别了。这篇博客就一起学习这两个方法
sleep()
下面用一个例子来演示:
Service类:
public class Service { public void mSleep(){ synchronized(this){ try{ System.out.println(" Sleep 。当前时间:"+System.currentTimeMillis()); Thread.sleep(3*1000); } catch(Exception e){ System.out.println(e); } } } public void mWait(){ synchronized(this){ System.out.println(" Wait 。结束时间:"+System.currentTimeMillis()); } } }
就定义了两个方法, mSleep()方法会让调用线程休眠3秒,mWait() 就打印一句话。两个方法都使用了同步锁。
SleepThread类:
public class SleepThread implements Runnable{
private Service service; public SleepThread(Service service){ this.service = service; } public void run(){ service.mSleep(); } }
线程类,用于调用Service 的mSleep方法
WaitThread类:
public class WaitThread implements Runnable{
private Service service; public WaitThread(Service service){ this.service = service; } public void run(){ service.mWait(); } }
线程类,用于调用Service 的mWait方法
测试类:
public class Test{ public static void main(String[] args){ Service mService = new Service(); Thread sleepThread = new Thread(new SleepThread(mService)); Thread waitThread = new Thread(new WaitThread(mService)); sleepThread.start(); waitThread.start(); } }
梳理一下逻辑:
如果sleepThread释放了机锁的话,waitThread 的任务会马上得到执行。从打印结果可以看出,waitThread 的任务是3秒钟之后才得到执行。
synchronized(this){ System.out.println(" Wait 。结束时间:"+System.currentTimeMillis()); }
相信现在你已经理解了sleep方法没有释放机锁会带来什么结果了,那么继续wait
wait()
wait()是Object类的方法,当一个线程执行到wait方法时,它就进入到一个和该对象相关的等待池,同时释放对象的机锁,使得其他线程能够访问,可以通过notify,notifyAll方法来唤醒等待的线程
下面修改程序如下所示:
public class Service { public void mSleep(){ synchronized(this){ try{ Thread.sleep(3*1000); this.notifyAll(); System.out.println(" 唤醒等待 。 结束时间:"+System.currentTimeMillis()); } catch(Exception e){ System.out.println(e); } } } public void mWait(){ synchronized(this){ try{ System.out.println(" 等待开始 。 当前时间:"+System.currentTimeMillis()); this.wait(); }catch(Exception e){ System.out.println(e); } } } }
测试类:
public class Test{ public static void main(String[] args){ Service mService = new Service(); Thread sleepThread = new Thread(new SleepThread(mService)); Thread waitThread = new Thread(new WaitThread(mService)); waitThread.start(); sleepThread.start(); } }
这里是先让 waitThread线程启动起来,然后waitThread线程进入等待状态,并释放了Service对象的锁,这时sleepThread也启动了,来到了mSleep方法的同步代码块,因为之前的waitThread线程已经释放了Service对象的机锁,sleepThread可以拿到对象锁,所以mSleep方法是会被马上调用的。然后sleepThread线程就是进入了睡眠状态,等到3秒休眠结束后调用notifyAll()唤醒了waitThread线程。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/221695.html原文链接:https://javaforall.net
