Java Design Demo--多线程(一)线程唤醒

package demo1.test1;

public class Test {

	/**
	 * synchronized wait() notify唤醒示例
	 * 
	 * @param args
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		
		
		final Object obj1 = new Object();
		final Object obj2 = new Object();
		new Thread() {
			@Override
			public void run() {
				synchronized (obj1) {
					try {
						obj1.wait();
					} catch (InterruptedException e) {
					}
					System.out.println("1");
				}
			}

		}.start();
		new Thread() {
			@Override
			public void run() {
				synchronized (obj2) {
					try {
						obj2.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("2");
				}
			}

		}.start();
		Thread.sleep(1000);
		synchronized (obj2) {
			obj2.notify();
		}

	}

}
必须在synchronized中指定的锁对像进行等待和唤醒,以上代码打印结果为2;

你可能感兴趣的:(Java Design Demo--多线程(一)线程唤醒)