JavaDemo——线程协作await、signal、signalAll

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/FlyLikeButterfly/article/details/81912328
  1. Lock接口的实现:Lock lock = new ReentrantLock();
  2. Condition接口依靠Lock对象:Condition condition = lock.newCondition();
  3. lock.lock()和lock.unlock()加锁和释放,unlock()通常放在finally里。
  4. Condition的await()、signal()、signalAll()要放在lock()和unlock()锁内。

测试Demo:

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

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * TODO
 * @author XWF
 */
public class TestLock2 {
	
	private Lock lock = new ReentrantLock();
	private Condition lockCondition = lock.newCondition();
	
	private int result;

	public int start() {
		System.out.println("start");
		result = -1;
		lock.lock();
		System.out.println("start condition.await 3s");
		try {
			lockCondition.await(3,TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
			return result;
		}finally {
			lock.unlock();//异常也得释放锁
		}
		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) {
			lock.lock();
			result = x;
			System.out.println("stop condition.signal 结果:"+result);
			lockCondition.signal();
			lock.unlock();
		}
	}
	
	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		TestLock2 test1 = new TestLock2();
		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("===========================================");
		TestLock2 test2 = new TestLock2();
		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("===========================================");
		TestLock2 test3 = new TestLock2();
		new Thread(new Runnable() {
			@Override
			public void run() {
				test3.start();
			}
		}).start();
		Thread.sleep(3500);
		new Thread(new Runnable() {
			@Override
			public void run() {
				test3.stop(0);
			}
		}).start();
	}

}

结果:

猜你喜欢

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