为什么线程按此顺序工作?

时间:2016-03-14 21:52:44

标签: java multithreading

我有3个课程:主要来电 CallMe 来电者实施可运行。我向来电者构建器传递指向 CallMe 实例的指针以及来电者传递给 CallMe 实例方法的消息>打印消息。接下来,我开始一个线程。

主要中,我创建了来电者的3个实例,我将在此处打印:

[Welcome]
[to synchronized]
[world!]

但我得到以下结果:

[Welcome]
[world!]
[to synchronized]

为什么吗

有代码:

Main.java

public class Main {
    public static void main(String[] args) {
        CallMe target = new CallMe();
        Caller ob1 = new Caller(target, "Welcome");
        Caller ob2 = new Caller(target, "to synchronized");
        Caller ob3 = new Caller(target, "world!");

        try {
            ob1.thread.join();
            ob2.thread.join();
            ob3.thread.join();
        } catch (InterruptedException exc) {
            System.out.println(exc);
        }
    }
}

Caller.java

public class Caller implements Runnable {
    String message;
    CallMe target;
    Thread thread;

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

    public void run() {
        synchronized (target) {
            target.call(message);
        }
    }
}

CallMe.java

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

1 个答案:

答案 0 :(得分:5)

主方法中Caller的三个实例化可能都发生在一个时间片内,即没有屈服于另一个线程。这导致创建所有三个线程并将其置于可运行状态。之后,可以按任何顺序安排线程,所以你只是运气不好。

如果您希望线程按特定顺序执行,则需要自己提供互锁逻辑。

相关问题