It seems like this code is not correct:
class Demonstration {
static Thread firstThread = null; public static void main( String args[] ) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(50); try { for (int i = 0; i < 25; i++) { executor.submit(new Runnable() { @Override public void run() { synchronized (this) { if (firstThread == null) { firstThread = Thread.currentThread(); System.out.println(Thread.currentThread().getName() + " takes first turn"); } } } }); } } finally { executor.shutdown(); executor.awaitTermination(1, TimeUnit.HOURS); } }
}
To work as expected it should be synchronized not on THIS which is an instance of each submitted runnable itself, but on some shared object like Deonsytation.class.