I am new to multithreading, and I wrote this code which prints the numbers 1-10000 by having concurrently running threads increment and print a variable.
Here’s the code I’m using:
package threadtest;
public class Main{
static int i=0;
static Object lock=new Object();
private static class Incrementer extends Thread{
@Override
public void run(){
while (true){
synchronized(lock){
if (i>=10000)
break;
i++;
System.out.println(i);
}
}
}
}
public static void main(String[] args) {
new Incrementer().start();
new Incrementer().start();
new Incrementer().start();
new Incrementer().start();
new Incrementer().start();
new Incrementer().start();
}
}
This works – I wrote up a test program to check the output, and the numbers printed are exactly 1-10000 in order.
My question is this: I’ve heard that synchronized is only syntactic sugar. But I can’t seem to achieve a successful result without using it. What am I missing?
synchronizedis by no means syntactic sugar for anything. There is no way to work locks in Java without using thesynchronizedkeyword.Where there is “syntactic sugar” of a sort in locks in Java is that
synchronizedcan apply both to blocks (as you’ve done it above) and to whole methods. The following two methods are roughly equivalent in semantics:So why would you want to do the second version instead of the first?
thisfor locking which gives you more flexible locking semantics.