packagecom.lw;
importjava.util.concurrent.locks.Lock;
importjava.util.concurrent.locks.ReentrantLock;
publicclassReentrantLockDemoimplementsRunnable{
privateintnumber=0;//创建一个变量
privateLocklock=newReentrantLock();//创建重入锁对象
@Override
publicvoidrun(){
lock.lock();//打开锁
try{
for(inti=0;i<5;i++){
try{
Thread.sleep(100);//线程休眠0.1秒
}catch(InterruptedExceptione){
e.printStackTrace();
}
//输出当前线程的名称和number的值,每次循环之后number的值都会加一
System.out.println(Thread.currentThread().getName()+":"
+number++);
}
}finally{
lock.unlock();//释放锁
}
}
publicstaticvoidmain(String[]args){
ReentrantLockDemorun=newReentrantLockDemo();//获得ReentrantLockDemo对象
Threadthread1=newThread(run);//创建线程1
Threadthread2=newThread(run);//创建线程2
thread1.start();//运行线程1
thread2.start();//运行线程2
}
}