使用Lock解决线程安全问题
package com.zr;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
使用Lock解决线程安全问题
*/
public class RunnableImpl implements Runnable {
//票的总数量
private int tickets=100;
//定义锁
Lock l=new ReentrantLock();
@Override
public void run() {
while (true){
l.lock();//开启锁
try {
if (tickets>0){
System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets+"张票");
}
tickets--;
}catch (Exception e){
e.printStackTrace();
}finally {
l.unlock();//释放锁
}
}
}
}
演示使用Lock解决线程安全问题
package com.zr;
//演示使用Lock解决线程安全问题
public class DemoLock {
public static void main(String[] args) {
//创建Runnable接口的实现类对象RunnableImpl
RunnableImpl run=new RunnableImpl();
//定义三个线程
Thread t1=new Thread(run);
Thread t2=new Thread(run);
Thread t3=new Thread(run);
//调用start方法开启多线程
t1.start();
t2.start();
t3.start();
}
}