如果按下面的方式写lock,你会发现lock并没有起到作用。
public static class count{
// private int i ;
public void get(){
final ReentrantLock lock = new ReentrantLock(); //lock 声明在函数内
try{
lock.lock();
System.out.println(Thread.currentThread().getName()+" get begin");
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+" get end");
lock.unlock();
}catch(InterruptedException e){
e.printStackTrace();
}
}
public void put(){
final ReentrantLock lock = new ReentrantLock(); //lock 声明在函数内
try{
lock.lock();
System.out.println(Thread.currentThread().getName()+" put begin");
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+" put end");
lock.unlock();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
结果如下:
Thread-0 put begin
Thread-1 put begin
Thread-2 get begin
Thread-3 get begin
Thread-3 get end
Thread-0 put end
Thread-1 put end
Thread-2 get end
原因在于lock的声明在函数内,线程调用函数得到的lock值互不影响,所有并没有实现互斥。
改为如下:
public static class count{
final ReentrantLock lock = new ReentrantLock(); //lock 声明在函数外
public void get(){
try{
lock.lock();
System.out.println(Thread.currentThread().getName()+" get begin");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" get end");
lock.unlock();
}catch(InterruptedException e){
e.printStackTrace();
}
}
public void put(){
try{
lock.lock();
System.out.println(Thread.currentThread().getName()+" put begin");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" put end");
lock.unlock();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
结果如下:
Thread-0 get begin
Thread-0 get end
Thread-1 get begin
Thread-1 get end
Thread-2 put begin
Thread-2 put end
Thread-3 put begin
Thread-3 put end