import java.util.concurrent.*; import java.util.concurrent.locks.*; public class TestLock { public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); LockSample ls = new LockSample(); executor.execute(() -> ls.func()); executor.execute(() -> ls.func()); executor.shutdown(); } } class LockSample { private Lock lock = new ReentrantLock(); public void func() { lock.lock(); try { for (int i = 0; i < 5; i++) { System.out.println(i); Thread.sleep(10); } } catch (Exception e) { } finally { lock.unlock(); } } }