java线程(jdk5升级解决方案)


jdk5提供了将同步synchronized替换成了现实Lock操作。将Object中的wait,notify,notifyAll,替换了Condition对象,该实例实现了本方唤醒对方操作

代码如下:

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

/**
 * 生产消费者问题
 * 
 * jdk 1.5之后提供了多线程升级解决方案
 * 
 *	1.将同步synchronized替换成 lock操作
 *	2.将Object中的wait(),notify(),notifyAll()替换成了Condition该对象可以用lock来得到
 *	3.该实例中实现了本方唤醒对方操作
 * 
 * @author Yxx
 *
 */
public class ConditionThread2 {
	public static void main(String agrs[]){
		Res3 r = new Res3();
		Producer1 p = new Producer1(r);
		Consumer1 c = new Consumer1(r);
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(c);
		Thread t3 = new Thread(p);
		Thread t4 = new Thread(c);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}


/**
 * 资源
 * @author Yxx
 *
 */
class Res3{
	private String name;
	boolean flag = false;
	ReentrantLock lock = new ReentrantLock();
	private Condition con1 = lock.newCondition();
	private Condition con2 = lock.newCondition();
	public void set(String name)throws IllegalMonitorStateException{
		lock.lock();		//得到同步锁
		try{
		while(flag)
			try {
				con1.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		this.name = name;
		System.out.println("生产者生产了商品--------------->"+this.name);
		flag = true;
		con2.signal();
		}finally{
			lock.unlock();//释放解锁
		}
	}
	
	public void out(){
		lock.lock();		//得到同步锁
		try{
			while(!flag)
					con2.await();
			System.out.println("消费者消费了商品-------------------------------------------->"+this.name);
			flag = false;
			con1.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			lock.unlock();			//释放解锁
		}
	}
}

/**
 * 生产者
 * @author Yxx
 *
 */
class Producer1 implements Runnable{
	Res3 r;
	public Producer1(Res3 r){
		this.r = r;
	}
	public void run() {
		while(true){
			r.set("商品");
		}
	}
}

class Consumer1 implements Runnable{
	Res3 r;
	public Consumer1(Res3 r){
		this.r = r;
	}
	public void run(){
		while(true){
			r.out();
		}
	}
}

  • 大小: 29.7 KB
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值