JavaDemo——线程协作wait、notify、notifyAll

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/FlyLikeButterfly/article/details/81875524
  1. wait()、notify()、notifyAll()是Object对象的final方法。
  2. 必须在拿到锁的情况下使用(同步块中)。
  3. wait(),立即释放锁并进入阻塞。
  4. notify(),只是唤醒一个阻塞线程(如果有多个wait则随机一个)并不立即释放锁,待notify()同步块运行完释放锁,唤醒的线程才可以重新获得锁。
  5. notifyAll(),唤醒所有阻塞线程并不立即释放锁,唤醒的线程由系统调度获得锁。

测试Demo:

/**
 * createtime : 2018年8月20日 下午3:04:36
 */
package locktest;

/**
 * TODO
 * @author XWF
 */
public class TestLock1 {

	private Object lockObj = new Object();
	
	private int result;//-1异常,0成功,1失败,2超时
	
	public int start() {
		System.out.println("start");
		result = -1;
		synchronized (lockObj) {
			System.out.println("start wait 3000ms");
			try {
				lockObj.wait(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				return result;
			}
		}
		if(result == -1) {
			result = 2;//超时
			System.out.println("start 超时:"+result);
			return result;
		}else if(result == 0 || result == 1){
			System.out.println("start 结果:"+result);
			return result;
		}else {
			result = -1;
			System.out.println("start 异常结果:"+result);
			return result;
		}
	}
	
	public void stop(int x) {
		System.out.println("stop");
		if(result != 2) {//非超时
			synchronized (lockObj) {
				result = x;
				System.out.println("stop notify 结果:"+result);
				lockObj.notify();
			}
		}
	}
	
	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		TestLock1 test1 = new TestLock1();
		new Thread(new Runnable() {
			@Override
			public void run() {
				test1.start();
			}
		}).start();
		Thread.sleep(2000);
		new Thread(new Runnable() {
			@Override
			public void run() {
				test1.stop(0);
			}
		}).start();
		Thread.sleep(5000);
		System.out.println("===========================================");
		TestLock1 test2 = new TestLock1();
		new Thread(new Runnable() {
			@Override
			public void run() {
				test2.start();
			}
		}).start();
		Thread.sleep(2000);
		new Thread(new Runnable() {
			@Override
			public void run() {
				test2.stop(1);
			}
		}).start();
		Thread.sleep(5000);
		System.out.println("===========================================");
		TestLock1 test3 = new TestLock1();
		new Thread(new Runnable() {
			@Override
			public void run() {
				test3.start();
			}
		}).start();
		Thread.sleep(3500);
		new Thread(new Runnable() {
			@Override
			public void run() {
				test3.stop(1);
			}
		}).start();
	}

}

结果:

猜你喜欢

转载自blog.csdn.net/FlyLikeButterfly/article/details/81875524