//1.创建ReentrantLock对象
Lock alook = new ReentrantLock();
//2.方法前加锁
alook.lock();
//......具体方法代码
//3.方法后释放锁
alook.unlock();
public class DemoThread implements Runnable {
private static Integer ticker = 100;
// 1.创建ReentrantLock对象
Lock l = new ReentrantLock();
@Override
public void run() {
while (true) {
//方法前加锁
l.lock();
/********************存在线程安全问题的代码************************/
try {
//...省略代码
} catch (Exception e) {
e.printStackTrace();
}
/****************************************************************/
//这种写法能保证无论是否异常都释放锁
finally {
//方法后释放锁
l.unlock();
}
}
}