I get a fixed number of two threads, then submitted 100 tasks, inside which I
used a lock and intentionally leave it unlocked, running result of this code is
sorted number from 1 to 99, this makes me confused:
1) Is it because the thread is reused so that the same thread can acquire it multiple times?
2) If so, lock does not block thread, it still can be reused? What the lock guards is only the lines within its scope.
Please correct me.
public class LockTest {
public static volatile int a = 1;
static final ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int k = 0; k < 100; k++) {
executorService.submit(new Runnable() {
@Override
public void run() {
lock.lock();
System.out.println(a++);
}
});
}
executorService.shutdown();
}
}