使用Condition唤醒指定种类线程

package com.freeflying.thread.reentrantlock;

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

public class ConditionNoticePartThread {
	public static void main(String[] args) {
		ConditionNoticePartThreadEX conditionNoticePartThreadEX=new ConditionNoticePartThreadEX();
		ConditionNoticePartThreadA threadExA=new ConditionNoticePartThreadA(conditionNoticePartThreadEX);
		threadExA.setName("A");
		threadExA.start();
		ConditionNoticePartThreadB threadExB=new ConditionNoticePartThreadB(conditionNoticePartThreadEX);
		threadExB.setName("B");
		threadExB.start();
		conditionNoticePartThreadEX.singnalAll_A();
	}
}
class ConditionNoticePartThreadEX{
	private Lock lock=new ReentrantLock();
	public Condition conditionA=lock.newCondition();
	public Condition conditionB=lock.newCondition();
	public void awaitA() {
		try {
			lock.lock();
			System.out.println("begin awaitA time is:"+System.currentTimeMillis()+"ThreadName:"+Thread.currentThread().getName());
			conditionA.await();
			System.out.println("end awaitA time is:"+System.currentTimeMillis()+"ThreadName:"+Thread.currentThread().getName());
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
	}
	public void awaitB() {
		try {
			lock.lock();
			System.out.println("begin awaitB time is:"+System.currentTimeMillis()+"ThreadName:"+Thread.currentThread().getName());
			conditionA.await();
			System.out.println("end awaitB time is:"+System.currentTimeMillis()+"ThreadName:"+Thread.currentThread().getName());
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
	}
	public void singnalAll_A() {
		try {
			lock.lock();
			System.out.println("singnalAll_A time is:"+System.currentTimeMillis()+"ThreadName:"+Thread.currentThread().getName());
			conditionA.signal();
		} finally {
			lock.unlock();
		}
	}
	public void singnalAll_B() {
		try {
			lock.lock();
			System.out.println("singnalAll_B time is:"+System.currentTimeMillis()+"ThreadName:"+Thread.currentThread().getName());
			conditionB.signal();
		} finally {
			lock.unlock();
		}
	}
}
class ConditionNoticePartThreadA extends Thread{
	private ConditionNoticePartThreadEX conditionNoticePartThreadEX;

	public ConditionNoticePartThreadA(ConditionNoticePartThreadEX conditionNoticePartThreadEX) {
		super();
		this.conditionNoticePartThreadEX = conditionNoticePartThreadEX;
	}
	@Override
	public void run() {
		conditionNoticePartThreadEX.awaitA();
	}
}
class ConditionNoticePartThreadB extends Thread{
	private ConditionNoticePartThreadEX conditionNoticePartThreadEX;

	public ConditionNoticePartThreadB(ConditionNoticePartThreadEX conditionNoticePartThreadEX) {
		super();
		this.conditionNoticePartThreadEX = conditionNoticePartThreadEX;
	}
	@Override
	public void run() {
		conditionNoticePartThreadEX.awaitB();
	}
}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页