多线程同步 生产消费者模式


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import cnwh.xbkj.kqwxfg.web.utils.ConvertTools;

public class ActiveData {

	private boolean flag = false;

	private final Lock lock = new ReentrantLock();

	private final Condition cond_SRO = lock.newCondition();
	private final Condition cond_FRR = lock.newCondition();

	public void SendReqOrder() throws InterruptedException {
		lock.lock();
		try {
			while (flag)
				cond_SRO.await();// 如果当前标记是true,发送命令的线程进行等待!
			flag = true;// 将标记设置为true;
			cond_FRR.signal();// 唤醒接受消息的线程;
		} finally {
			lock.unlock();// 释放锁;
		}
	}

	public String fetchReceiveResult() throws InterruptedException {
		lock.lock();
		StringBuffer sb = new StringBuffer();
		try {
			while (!flag)
				cond_FRR.await();// 当前标记是false,接受消息的线程进行等待!
			// 处理接受的消息code

			flag = false;// 将标记设置为false;
			cond_SRO.signal();
		} finally {
			lock.unlock();
		}
		return null;
	}
}

你可能感兴趣的:(生产消费者,多线程同步)