Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java try-finally语法中的NPE_Java - Fatal编程技术网

Java try-finally语法中的NPE

Java try-finally语法中的NPE,java,Java,下面是我测试一些语法的代码。我想在try块中返回一个对象,并在finally块中执行一些操作。但是当我运行代码时,我得到了NullPointException。原因是使用了ReentrantLock,但我不知道为什么 import java.util.concurrent.locks.ReentrantLock; public class Main { ReentrantLock lock; public static void main(String[] args) {

下面是我测试一些语法的代码。我想在try块中返回一个对象,并在finally块中执行一些操作。但是当我运行代码时,我得到了NullPointException。原因是使用了
ReentrantLock
,但我不知道为什么

import java.util.concurrent.locks.ReentrantLock;


public class Main {

  ReentrantLock lock;

  public static void main(String[] args) {
    try {
      new Main().run();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void run() {
      System.out.println(returnTest().get());
  }

  A returnTest(){
//  lock.lock();
    try {
      return new A();
    } finally {
//  lock.unlock();
    }
  }

}

class A {
  public boolean get() {
    return true;
  }
}
如果我取消注释
lock.lock()
lock.unlock()
,我将得到NullPointException。
为什么?

因为
可重入锁定锁从未实例化/初始化

在开始时初始化它

ReentrantLock lock = new ReentrantLock();

因为
ReentrantLock锁从未实例化/初始化

在开始时初始化它

ReentrantLock lock = new ReentrantLock();

您需要初始化ReentrantLock类的对象

做:

ReentrantLock lock = new ReentrantLock();

您需要初始化ReentrantLock类的对象

做:

ReentrantLock lock = new ReentrantLock();

按如下方式初始化锁变量:

private final ReentrantLock lock  = new ReentrantLock();

基本上会引发NullPointException,因为锁是用null值初始化的,所以这就是为什么应该初始化的原因。

像这样初始化锁变量:

private final ReentrantLock lock  = new ReentrantLock();
基本上会引发NullPointException,因为锁是用null值初始化的,所以应该初始化