Ok, the problem is that the synchronized keyword on a method synchronizes that method
for that object. When you say new iocheck().start(), you are creating an object. Since you do that twice, you end up with 2 objects running their own code. Make sense?
To make this code work without putting the synchronized blocks in like Kevin did, change your iocheck class to implement Runnable instead of extending Thread. Then in your main, try the following:
iocheck ioc = new iocheck();
new Thread(ioc).start();
new Thread(ioc).start();
The reason this works is because both Threads are trying to access the same run method of the
same object, instead of 2 different ones (as in your code). So the second thread has to wait until the first thread releases the lock to that object's code. Then you will get the 123456789 123456789 output.
Basically, you're looking at the difference between a
class lock and an
object lock. A class lock operates on synchronized static blocks (including methods) in a class. An object lock operates on synchronized non-static methods.
Good luck on your exam!
April