I began to learn Java from the book of Shildt (Java 8 Complete Handbook 9 of ezd). The topic of multi-threaded programming says:
Ie it turns out 2 threads can not simultaneously work with synchronized methods of the object. By writing code to check:
//T1, T2 - потоки //q объект класса Q, с которым работают потоки //В потоке Т1 50 раз должно вывестисть One //В потоке T2 50 раз должно вывестисть Two class Q{ synchronized void print1(){ System.out.println("One"); } synchronized void print2(){ System.out.println("Two"); } } class T1 implements Runnable{ Q q; T1(Q q){ this.q = q; new Thread(this).start(); } public void run(){ for(int i = 0; i < 50; i++){ q.print1(); } } } class T2 implements Runnable{ Q q; T2(Q q){ this.q = q; new Thread(this).start(); } public void run(){ for(int i = 0; i < 50; i++){ q.print2(); } } } public class main { public static void main(String args[]) throws InterruptedException{ Q q = new Q(); new T1(q); new T2(q); } } I got the following:
... One One Two Two Two One One ... Why is switching from one thread to another and back? Is there a contradiction to what is written in the book? Methods synchronized and it turns out the 2nd thread should wait for the 1st thread to finish working with the object, or did I misunderstand something?