H
H
hudrogen2017-04-06 17:33:14
Java
hudrogen, 2017-04-06 17:33:14

Why doesn't the method synchronization example from Schildt's book Java 8 work?

Implementing examples from Schildt's book "Java 8 The Complete Guide"
Chapter 11 Using Synchronized Methods pp. 301-302.
Expected to output [Welcome][to the synchronized][world!] to the console.
In fact, the output sequence is jumbled and does not match join() calls.
There are 3 classes

public class CallMe {
    synchronized void call(String msg){
        System.out.print("[" + msg);
        try {
            Thread.sleep(2000);
        } catch (Exception e) {
            System.out.println("Прервано");
        }
        System.out.println("]");
    }
}

public class Caller implements Runnable {
    String msg;
    CallMe target;
    Thread t;

    public Caller(CallMe target, String msg) {
        this.target = target;
        this.msg = msg;
        t = new Thread(this);
        t.start();
    }

    @Override
    public void run() {
        target.call(msg);
    }
}

public class Synch {
    public static void main(String[] args) {
        CallMe target = new CallMe();
        Caller ob1 = new Caller(target, "Добро пожаловать");
        Caller ob2 = new Caller(target, "в снхронизированный");
        Caller ob3 = new Caller(target, "мир!");

        try {
            ob1.t.join();
            ob2.t.join();
            ob3.t.join();
        } catch (InterruptedException e) {
            System.out.println("Прервано в синхронизации!");
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Kosarev, 2017-04-07
@hudrogen

Because in the example the call method of the CallMe class is not synchronized, but yours is synchronized

D
Denis Zagaevsky, 2017-04-06
@zagayevskiy

I don’t know what Schildt has there, but this code will not work, as you say. Three threads start and perform work in random order. The fact that they join in this order does not affect at all. Perhaps this is an example of what not to do.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question