Skip to content

Commit 2428f62

Browse files
committed
Lock examples
1 parent 83db082 commit 2428f62

File tree

1 file changed

+14
-1
lines changed
  • src/com/winterbe/java8/samples/concurrent

1 file changed

+14
-1
lines changed

src/com/winterbe/java8/samples/concurrent/Lock2.java

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.concurrent.ExecutorService;
44
import java.util.concurrent.Executors;
5+
import java.util.concurrent.TimeUnit;
56
import java.util.concurrent.locks.ReentrantLock;
67

78
/**
@@ -18,11 +19,23 @@ public static void main(String[] args) {
1819
lock.lock();
1920
try {
2021
System.out.println(lock.isLocked());
21-
} finally {
22+
TimeUnit.SECONDS.sleep(1);
23+
}
24+
catch (InterruptedException e) {
25+
throw new IllegalStateException(e);
26+
}
27+
finally {
2228
lock.unlock();
2329
}
2430
});
2531

32+
executor.submit(() -> {
33+
System.out.println("Locked: " + lock.isLocked());
34+
System.out.println("Held by me: " + lock.isHeldByCurrentThread());
35+
boolean locked = lock.tryLock();
36+
System.out.println("Lock acquired: " + locked);
37+
});
38+
2639
ConcurrentUtils.stop(executor);
2740
}
2841

0 commit comments

Comments
 (0)