我正在学习编写更好的多线程程序,线程安全和确定性。我碰到这段代码多线程:为什么输出?它是确定性的吗?
// File Name : Callme.java
// This program uses a synchronized block.
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
// File Name : Caller.java
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}
}
}
// File Name : Synch.java
public class Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
产生以下输出(试过〜100倍)
[Hello]
[World]
[Synchronized]
所以我的第一个问题是,这是保证输出?我还观察到,如果我改变睡眠100
它仍然产生相同的输出,但如果我改变睡眠10
输出变为
[Hello]
[Synchronized]
[World]
第二个问题是,如果它是有保证的,为什么呢?最后但并非最不重要的,为什么这个输出?我预计它是
[Hello]
[Synchronized]
[World]
您需要先编辑outputBuffer。然后冲洗它。 –
@ huseyintugrulbuyukisik-outputBuffer? – vidit
你是否在同步所有线程,例如:当第一个线程完成时,它表明第二个线程要写入。第二完成和信号第三写。 –