publicclassT3{finalObject lock =newObject();List<String> list =newArrayList<>();publicstaticvoidmain(String[] args){var e =newT3();var t =newThread(e::add,"工作");
t.start();var c =newThread(e::count,"统计");
c.start();}voidadd(){String t =Thread.currentThread().getName();System.out.printf("%s线程启动%n", t);synchronized(lock){for(int i =0; i <10; i++){//工作线程向集合中添加数据try{TimeUnit.SECONDS.sleep(1);}catch(Exception e){
e.printStackTrace();}String item =String.format("Item-%02d", i +1);
list.add(item);System.out.println(item);if(list.size()==5){//当加入5个数据后统计线程进行提示try{
lock.wait();//释放lock是当前线程陷入沉睡}catch(Exception e){
e.printStackTrace();}}}
lock.notifyAll();}System.out.printf("%s线程工作完成%n", t);}voidcount(){String t =Thread.currentThread().getName();System.out.printf("%s线程启动%n", t);synchronized(lock){try{System.out.printf("%S线程,统计到%d个元素%n", t, list.size());
lock.notifyAll();//唤醒所有沉睡线程
lock.wait();//释放lock是当前线程陷入沉睡}catch(Exception e){
e.printStackTrace();}}System.out.printf("%S线程工作结束%n", t, list.size());}}