class Callme {
synchronized void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}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();
}
public void run() {
target.call(msg);
}
}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");
}
}
}
这段代码不是应该输出
[Hello
]
[Synchronized
]
[World
]
吗?
怎么试了好几次都是输出
[Hello
]
[World
]
[Synchronized
]
有时输出
[Synchronized
]
[Hello
]
[World
]Java线程
synchronized void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}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();
}
public void run() {
target.call(msg);
}
}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");
}
}
}
这段代码不是应该输出
[Hello
]
[Synchronized
]
[World
]
吗?
怎么试了好几次都是输出
[Hello
]
[World
]
[Synchronized
]
有时输出
[Synchronized
]
[Hello
]
[World
]Java线程
synchronized void call(String msg) {
这个方法加锁了
第一个对象运行,运行的过程中休眠一秒。
因为对象target唯一,所以这一秒的时间里面ob2和ob3肯定都运行到等待运行call这个方法。
所以一秒过后就看哪个对象先抢占运行call方法了。
这样输入楼主的就很正常了。