`
Aga
  • 浏览: 217723 次
  • 性别: Icon_minigender_1
  • 来自: 天津
社区版块
存档分类
最新评论

Differences Between notify() and notifyAll()

    博客分类:
  • J2SE
阅读更多
package com.cxz.currency.test;

public class Testee implements Runnable {

	Object lock = null;

	public boolean runFlag = false;

	public Testee(Object lock) {
		this.lock = lock;
	}

	public void run() {
		synchronized (lock) {
			try {
				if (!runFlag) {
					lock.wait();
				}
				System.out.println("Hello" + Thread.currentThread().getName());
			} catch (InterruptedException ex) {

			}
		}
	}

	public void start() {
		Thread thread = new Thread(this);
		thread.start();
	}
}

package com.cxz.currency.test;

public class Main {
	public void test() throws InterruptedException{
		Object lock = new Object();
		Testee[] ts = new Testee[2];
		ts[0] = new Testee(lock);
		ts[1] = new Testee(lock);
		ts[0].start();
		ts[1].start();
		Thread.sleep(100);
		synchronized (lock) {
			lock.notify();
		}
		
	}
	public static void main(String[] args) throws InterruptedException{
		new Main().test();
	}
}

In the Main::test() I created 2 threads which were block at the lock.wait and after the main thread sleeped 100 milliseconds call the lock.notify and the lock.notifyAll you could see the differences.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics