java Lock接口详解及实例代码
java Lock接口
java.util.concurrent.locks
接口Lock
publicinterfaceLoce
Loce实现提供了比使用synchronized方法和语句可获得的更广泛的锁定操作
importjava.util.concurrent.locks.Lock; importjava.util.concurrent.locks.ReentrantLock; publicclassIntegerDemo{ publicstaticvoidmain(String[]args){ //创建3个线程对象 SellTicketst=newSellTicket(); Threadt1=newThread(st,"窗口1"); Threadt2=newThread(st,"窗口2"); Threadt3=newThread(st,"窗口3"); //启动线程 t1.start(); t2.start(); t3.start(); } } classSellTicketimplementsRunnable{ privateintticket=100; privateLocklock=newReentrantLock(); publicvoidrun(){ while(true){ lock.lock(); if(ticket>0){ try{ Thread.sleep(100); }catch(InterruptedExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"正在出售第"+(ticket--)+"张票。"); } lock.unlock(); } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!