Die Idee ist, eine ReentrantLock-Klasse zu implementieren, die das kann mit 'try with resources' verwendet werden und das bedeutet, dass es die AutoCloseable-Schnittstelle implementieren muss.
Außerdem wollte ich fragen, warum in der 'main'-Methode das Der Compiler gibt an, dass ich eine „catch“-Klausel hinzufügen muss, weil meine Die Methode close (in MyReentrantLock) löst keine Ausnahme aus.
Code: Select all
import java.util.concurrent.locks.ReentrantLock;
public class Ex09ReentrantLock {
@SuppressWarnings("serial")
public static class MyReentrantLock extends ReentrantLock implements AutoCloseable{
public MyReentrantLock() {
super();
lock();
}
@Override
public void close(){
unlock();
}
}
public static AutoCloseable lock() {
var locker = new MyReentrantLock(); //lock() is called in the constructor
return locker; //implements AutoCloseable
}
//Demo
public static void main(String[] args) {
//try(ReentrantLock lock = new ReentrantLock()){} = compiler error
try(var locker = lock();){
//some work...
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
- Ist diese Implementierung in Ordnung? (Rufen Sie die Sperre im Konstruktor auf...)
- Warum zwingt mich der Compiler, eine Catch()-Klausel hinzuzufügen, wenn mein Abschluss keine Klausel auslöst? Ausnahme?