package com.wuming.thread;import java.util.concurrent.locks.ReentrantLock;//测试Lock锁 public class TestLock {public static void main(String[] args) {TestLock2 testLock2 = new TestLock2();//多个对象操作同一个资源票,不用lock时线程不安全/* 108976543210-1*/new Thread(testLock2).start();new Thread(testLock2).start();new Thread(testLock2).start();} } class TestLock2 implements Runnable{int ticketNums=10;//定义lock锁private final ReentrantLock lock=new ReentrantLock();/*** When an object implementing interface <code>Runnable</code> is used* to create a thread, starting the thread causes the object's* <code>run</code> method to be called in that separately executing* thread.* <p>* The general contract of the method <code>run</code> is that it may* take any action whatsoever.** @see Thread#run()*/@Overridepublic void run() {while(true){try{lock.lock();//加锁后,使得线程安全/* 10987654321*/if (ticketNums>0){try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(ticketNums--);}else{break;}}finally{//解锁lock.unlock();}}} }