Java - Syncronized Thread - 以错误的顺序输出 [英] Java - Syncronized Thread - Output in wrong order

查看:95
本文介绍了Java - Syncronized Thread - 以错误的顺序输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Java The Complete Reference(第9版),这是在用Java愚弄一年之后。到目前为止对这本书很满意,但我现在对同步主题有一个非常奇怪的问题:

I'm reading Java The Complete Reference(9th Edition) after year of fooling around with Java. Been happy with the book so far but I now have a really strange problem with synchronized threads:

package syncro;

class Callme {
    void call(String msg) {
        System.out.print("[" + msg);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted");
        }
        System.out.println("]");
    }
}

class Caller1 implements Runnable {
    String msg;
    Callme target;
    Thread t;

    public Caller1(Callme targ, String s) {
        target = targ;
        msg = s;
        t = new Thread(this);
        t.start();
    }

    @Override
    public void run() {
        synchronized (target) { // SYNC BLOCK
            target.call(msg);
        }

    }
}

public class Syncronized {
    public static void main(String[] args) {
        Callme target = new Callme();
        Caller1 ob1 = new Caller1(target, "Hello");
        Caller1 ob2 = new Caller1(target, "Synchronized");
        Caller1 ob3 = new Caller1(target, "World");

        try {
            ob1.t.join();
            ob2.t.join();
            ob3.t.join();
        } catch (InterruptedException e) {
            System.out.println("Interrupted");
        }
    }

}

打印out:

[Hello]
[World]
[Synchronized]

我不明白这是怎么回事。另外值得一提的是,如果我换行

and I don't understand how that's even possible. Also worth mentioning, if I swap the lines

 Caller1 ob2 = new Caller1(target, "Synchronized");
 Caller1 ob3 = new Caller1(target, "World");

(在同步之前使用字符串World调用构造函数)
它将会打印

(constructor is called with the string "World" before "Synchronized") it will print

[Hello]
[Synchronized]
[World]

正如我原先预期的那样。

as I would have expected in the first place.

我没有在这里找到这样的问题所以我希望我做得对...谢谢!

I didn't find a question like this here so I hope I'm doing this right... Thanks!

推荐答案

简短的回答是您的 synchronized 块保证唯一的一件事就是您对 Callme.call 的3次调用将是相互排斥的 - 您赢了t(例如)同时调用 Thread.sleep 中的所有3个线程。它不能保证三个调用发生的顺序,事实上,有可能(尽管不太可能)多次运行未修改的代码可能导致在任何特定运行中以任何顺序输出3个单词。

The short answer is that the only thing your synchronized block guarantees is that your 3 calls to Callme.call will be mutually exclusive - you won't (for example) end up with all 3 of your threads in the Thread.sleep call simultaneously. It doesn't guarantee anything about the order in which the three calls will occur, and in fact it would be possible (though unlikely) that running your unmodified code multiple times could result in your 3 words being output in any order on any particular run.

这篇关于Java - Syncronized Thread - 以错误的顺序输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆