Synchronization with blocking in Java
//class field
static Random random = new Random();
static void showNumber(int number) {
//lock access for other threads
synchronized (random) {
try {
Thread.sleep(random.nextInt(500));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(number + ", ");
}
}
ExecutorService threahPool = Executors.newFixedThreadPool(10);
//start ten threads
for (int i = 1; i <= 10; i++) {
int number = i;
Runnable action = () -> {
showNumber(number);
};
threahPool.execute(action);
}
//result without lock: 9, 4, 7, 3, 2, 10, 6, 5, 1, 8
//result with lock: 1, 10, 9, 8, 7, 6, 5, 4, 3, 2,
- Log in to post comments