线程t1有一个控制线程t2的静态布尔变量s。t2是一个while循环通过判断s的值来决定是否终止。
现在t1希望等待t2终止后才终止,这个程序该怎么写?

解决方案 »

  1.   

    t1线程中也可以做个while循环,判断t2是否已经终止。如果t2终止了,t1也终止。
    t2是否已经终止如果判断不了,可以再加一个静态布尔变量,t2结束时才设置为true,t1通过这个变量判断是否终止。
      

  2.   

    一般不会这么用,用线程联合t1.join(t2)来实现这类线程同步问题
      

  3.   

    答:很简单。t1线程中最后一句代码是:t2.join()就行了。
      

  4.   

    import java.util.concurrent.atomic.AtomicBoolean;
    public class DriverTest {

    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {

    final AtomicBoolean run1 = new AtomicBoolean(true);

    new Thread(){

    Boolean run = true;

    public void run() {
    while(run){

    System.out.println("Thread 2 is still running");

    run = run1.get();

    }
    }
    }.start();

    Thread.sleep(3000);

    while(!run1.compareAndSet(true, false)){
    run1.compareAndSet(true, false);
    } }}