为什么reentrantLock没锁住
public class TestLock {
final ReentrantLock reentrantLock = new ReentrantLock(true);
private static int number;
void test(){
try {
reentrantLock.lock();
number++;
System.out.println(Thread.currentThread().getName()+" finished_"+number);
} catch (Exception e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
}
}
public class ThreadLock extends Thread{
private final Object object = new TestLock();
public ThreadLock(String threadName){
super(threadName);
}
public void run() {
if(object instanceof TestLock){
((TestLock) object).test();
}
}
public static void main(String[] args) {
Thread thread1 = new ThreadLock("thread1");
Thread thread2 = new ThreadLock("thread2");
Thread thread3 = new ThreadLock("thread3");
Thread thread4 = new ThreadLock("thread4");
Thread thread5 = new ThreadLock("thread5");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
结果竟然出现了重复数据:
"C:\Program Files\Java\jdk1.8.0_112\bin\java"
thread1 finished_2
thread2 finished_2
thread3 finished_3
thread5 finished_4
thread4 finished_4
Process finished with exit code 0
请问各位大神这是为什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你创建了多个ThreadLock对象,里面的TestLock对象都是不同的,所以锁不住
每个线程都是独立的lock对象,当然锁不住
排版看着难受,把你的 Lock 修改为全局静态的lock。