ConditionVariableExample里为什么"Waiting for the peer thread to finish."总是会先打印出来?而不是Hello, world?



  • ConditionVariableExample里为什么"Waiting for the peer thread to finish."总是会先打印出来?而不是Hello, world?



  • 求代码,如何重复error呢?



  • 此回复已被删除!


  • @Wenzhe

    public class ConditionVariableExample {
    private static final long SLEEP_INTERVAL_MS = 1000;
    private boolean running = true;
    private Thread thread;
    public void start() {
    thread = new Thread((Runnable) () -> {
    print(“Hello, world!”);
    try {
    Thread.sleep(SLEEP_INTERVAL_MS);
    } catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    }
    synchronized (ConditionVariableExample.this) {
    running = false;
    ConditionVariableExample.this.notify();
    }

    	});
    	thread.start();
    }
    public void join() throws InterruptedException {
    	synchronized (this) {
    		while(running) {
    			print("Waiting for the peer thread to finish.");
    			wait();//waiting, not running
    		}
    		print("Peer thread finished.");
    	}
    }
    private void print(String s) {
    	System.out.println(s);
    }
    public static void main(String[] args) throws InterruptedException {
    	ConditionVariableExample cve = new ConditionVariableExample();
    	cve.start();
    	cve.join();
    }
    

    }



  • @brucezhu 因为new Thread()是一个相对expensive的操作,要花一点时间。

    很好奇的是,为什么class的名字是ConditionVariableExample,但是里面用的是Object的synchronized+wait()/notifyAll(),而不是ReentrantLock+Condition.await()/signalAll()呢?是因为它们都统称为Condition Variable吗?


登录后回复
 

与 BitTiger Community 的连接断开,我们正在尝试重连,请耐心等待