Hi i am starting studying for SCJP and i was testing this code and seems strange for me.. i am using a runnable when i use the runnable interface PRINT method is synchronized but when i dont use Interface runnable and i use run method extending from Thread PRINT is not synchronized using the same Source code.. Sorry by my poor english.
It has to do with your Print() methods that you have declared as synchronized. Both methods synchronize on their class instances. You instantiate one MyRunnable instance and then create four Threads. All four threads are synchronizing on the same MyRunnable object so each one waits for the previous one to complete before continuing. You instantiate four instances of MyThreads. Your four threads are synchronizing on four different objects so none are waiting for any other. They are all running together.
BTW, it helps a lot to get answers on this forum when you UseCodeTags. Here's your code when using code tags:
Synchronizing a method will prevent this method to be called by the same instance from different threads.
Your first version (MyThreads a = new MyThreads();) is making four different instances of a class having the Print method. Each instance is calling its own Print method. There's no synchronization happening here. Your second version (MyRunnable Runnable = new MyRunnable()) uses only one instance having the Print method, and four threads. They all use the same Runnable instance, but as the method of that instance is synchronized, other threads will have to wait before being able to call the method in their turn.
thanks a lot Tom. look now i understand perfect my mistake in my previous code.. now what is wrong with synchronized code with Strings. because i use a string literal and synchronized perfect but for a new String Object (Using new string()) not synchronized as well. and i read some time ago strings literal doesn´t work for synchronized blocks what is wrong for synchronized blocks with strings.