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?

    1 answer 1

    They cannot run simultaneously. And they can be consistently executed.

    1. T1 calls print1() and thus blocks the object.
    2. T2 calls print2() , but the object is blocked and T2 waits.
    3. T1 exits print1() and unlocks the object.
    4. T2 starts print2() and blocks the object.
    5. The process is repeated.

    But not necessarily everything will happen alternately. It may be a situation that one of the threads will be executed more often, and the other less. This is not predictable.