2
回答
看下这段代码怎么会这样
滴滴云服务器,限时包月0.9元,为开发者而生>>>   

这段代码不是应该输出

[Hello

]

[Synchronizef

]

[World

]

吗?

怎么试了好几次都是输出

[Hello

[World

]

[Synchronized

]

有时输出

[Synchronized

]

[Hello

]

[World

]

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");
       }
    }
}

<无标签>
举报
痞子蔡
发帖于5年前 2回/171阅
共有2个答案 最后回答: 5年前
ob1.t.start();
ob2.t.start();
ob3.t.start();
ob1.t.join();
ob2.t.join();
ob3.t.join();
do something
在这种情况下,do something的处理会等到这三个线程都执行完,但是三个线程之间是独立的,它们的执行顺序是不确定的。如果你想要一个顺序地执行这三个线程,可以这样:
ob1.t.start();
ob1.t.join();
ob2.t.start();
ob2.t.join();
ob3.t.start();
ob3.t.join();

完整代码如下:

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);
	}

	public void run() {
		target.call(msg);
	}
}

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.start();
			ob1.t.join();
			ob2.t.start();
			ob2.t.join();
			ob3.t.start();
			ob3.t.join();
		} catch (InterruptedException e) {
			System.out.println("Interrupted");
		}
	}
}

--- 共有 2 条评论 ---
若海嗯,在绝大部分情况下,ob1是会被最先执行,但是多线程外加对象锁的时候,程序的并发执行是不可预知的。所以你在主线程中设定的顺序并不一定是你预期的。除非你在主线程中,用sleep方法,让所有子线程都有足够的时间去响应,这样也能有一种顺序执行的结果。 5年前 回复
痞子蔡ob1最先实例化,它的线程不是最先开始吗? 5年前 回复
顶部