2

请看下面的代码:

A级

package generalscenarios;

public class A implements Runnable{

    public void run(){

        System.out.println("dsad");

    }

}

B类

package generalscenarios;


public class B {


    public static void main(String[] args) throws InterruptedException {

        A a1  = new A();
        Thread a = new Thread(a1);
        a.start();
        System.out.println("hi");
    }
}

当我执行 B 类时,我的线程 a 将由主线程启动,并且 hi 将由主线程在控制台上打印。但是打印“hi”和“dsad”的顺序是不确定的。

我希望在“dsad”之后打印“hi”。

我想到的解决方案是在主线程和线程“a”之间取一个共享变量。主线程将等待该变量,直到线程“a”通知他。

A级

package generalscenarios;

public class A implements Runnable{

    public void run(){

        System.out.println("dsad");
        synchronized (this) {
            this.notify();  
        }


    }

}

B类

package generalscenarios;


public class B {


    public static void main(String[] args) throws InterruptedException {

        A a1  = new A();
        Thread a = new Thread(a1);
        a.start();
        synchronized (a1) {
            a1.wait();
        }
        System.out.println("hi");
    }
}

如果我的想法有效,请建议我。请提出任何其他方式来实现这一目标。

4

1 回答 1

6

你可以尝试类似的东西

public static void main(String[] args) throws InterruptedException {

    A a1  = new A();
    Thread a = new Thread(a1);
    a.start();
    a.join();
    System.out.println("hi");
}

请阅读Thread.join()并阅读Thread.

于 2012-05-18T08:57:53.360 回答