本帖最后由 王德南 于 2012-4-17 21:40 编辑
下面这段代码call()方法通过调用sleep()允许执行转换到另一个线程。为什么结果是3个字符串的混合输出的啊????
package com;
public class Demo6 {
public static void main(String[] args) {
Callme target=new Callme();
Caller ob1=new Caller(target, "Hello");
Caller ob2=new Caller(target, "Beauty");
Caller ob3=new Caller(target, "World");
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException");
}
}
}
class Callme{
void call(String message){
System.out.print("["+message);
try{
Thread.sleep(1000);
}catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String message;
Callme target;
Thread t;
public Caller(Callme targ,String s){
target=targ;
message=s;
t=new Thread(this);
t.start();
}
public void run() {
target.call(message);
}
}
为什么这样输出的啊???
为什么不是
[Hello]
[Beauty]
[World]
这种形式的啊 |
|