http://www.keepbase.com

这两种锁各有各的好处

如果强行的按照代码的书写顺序来执行指令,用如下代码来进行验证: publicstaticvoidmain(String[]args){Listlist=newLinkedList();Threadr=newThread(newReadList(list));Threadw=newThread(newWriteList(list));r.start();w.start();}classReadListimplementsRunnable{privateListlist;publicReadList(Listlist){this.list=list;}@Overridepublicvoidrun(){System.out.println(ReadListbeginat+System.currentTimeMillis());synchronized(list){try{Thread.sleep(1000);System.out.println(list.wait()beginat+System.currentTimeMillis());list.wait();System.out.println(list.wait()endat+System.currentTimeMillis());}catch(InterruptedExceptione){e.printStackTrace();}}System.out.println(ReadListendat+System.currentTimeMillis());}}classWriteListimplementsRunnable{privateListlist;publicWriteList(Listlist){this.list=list;}@Overridepublicvoidrun(){System.out.println(WriteListbeginat+System.currentTimeMillis());synchronized(list){System.out.println(getlockat+System.currentTimeMillis());list.notify();System.out.println(list.notify()at+System.currentTimeMillis());try{Thread.sleep(2000);}catch(InterruptedExceptione){e.printStackTrace();}System.out.println(getoutofblockat+System.currentTimeMillis());}System.out.println(WriteListendat+System.currentTimeMillis());}}

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。