这就是理论有余,实践不足么?

今天看到一个问题,两个线程,轮流交替输出1,2,1,2。。。

看似很简单是吧,就是条件控制么,果断最简单的wait和notify,但是一致报IllegalMonitorStateException,各种囧啊,各种试。最后发现是obj.wait()和obj.notify()必须放在synchronized块内。。之前真的真的从来没注意过这个细节。。。

public class TestPrint {

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

		final Object obj = new Object();

		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					while (true) {
						synchronized (obj) {
							obj.notifyAll();
							obj.wait();
							System.out.println(1);
						}
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					while (true) {
						synchronized (obj) {
							obj.notifyAll();
							obj.wait();
							System.out.println(2);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		t1.start();
		t2.start();
	};
}

One thought on “这就是理论有余,实践不足么?

Leave a Reply

Your email address will not be published. Required fields are marked *