JAVA同步-生产者与消费者实现 三

生产者消费者模型:

实现手段:在Condition类中 await()和 signalAll()方法实现:这种方式类似于 wait()和notifAll()的方法,但是此类方法实现                  有新特性,引入了Lock机制,动态的控制锁机制,来完成临界资源同步的线程运行;

问题描述:汽车打蜡抛光问题:一个汽车先打蜡再抛光也可以多次重复操作!

打蜡未完成时不能抛光,完成后通知抛光人员,才能抛光!

抛光未完成时不能打蜡,完成后通知打蜡人员,才能打蜡!

图示:

代码描写:

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

汽车类:

class Car {
	private Lock lock = new ReentrantLock(); 
	private Condition condition = lock.newCondition();
	private boolean WaxOn = false;
	//打蜡操作:
	public void waxed() {
		this.lock.lock();	// 加锁
		try {
			this.WaxOn = true;//打蜡完成:即可以抛光
			this.condition.signalAll();//通知可以抛光
		} finally {
		
			this.lock.unlock();//解锁
		}
	}
	//抛光操作:
	public void buff() {
		this.lock.lock();
		try {
			this.WaxOn = false;// 抛光完成:即可以打蜡
			this.condition.signalAll();//通知可以打蜡
		} finally {
			this.lock.unlock();
		}
	}
	//等待打蜡操作:
	public void waitingForWax() throws InterruptedException {
		this.lock.lock();
		try {
			while (this.WaxOn == false)
				this.condition.await();
		} finally {

			lock.unlock();
		}
	}
	//等待抛光操作:
	public void watingForBuffed() throws InterruptedException {
		this.lock.lock();
		try {
			while (this.WaxOn == true)
				this.condition.await();

		}  finally {
			this.lock.unlock();
		}
	}
}

打蜡类:

//打蜡线程:打蜡操作--通知抛光
class WaxOn implements Runnable {
	private Car car;

	public WaxOn(Car car) {
		this.car = car;
	}


	public void run() {
		try {
			while (!Thread.interrupted()) {
				System.out.print("Wax on!!");
				TimeUnit.MILLISECONDS.sleep(200);
				this.car.waxed();
				this.car.watingForBuffed();
			}
		} catch (Exception e) {
			e.printStackTrace();
			// System.out.println("Exiting via interrupted");
		}
		System.out.println("Ending Wax On task");
	}
}

抛光类:

//抛光线程:抛光操作--通知打蜡
class WaxOff implements Runnable {
	private Car car;

	public WaxOff(Car car) {
		this.car = car;
	}


	public void run() {
		try {
			while (!Thread.interrupted()) {
				car.waitingForWax();
				System.out.println("Wax Off!!");
				TimeUnit.MILLISECONDS.sleep(200);
				car.buff();
			}
		} catch (Exception e) {
			e.printStackTrace();
			// System.out.println("Exiting via interrupted");
		}
		System.out.println("Ending Wax Off task");
	}
}

线程启动:

public class WaxOnMatic2 {
	public static void main(String[] args) throws InterruptedException {
		Car car = new Car();
		ExecutorService exec = Executors.newCachedThreadPool();
		exec.execute(new WaxOn(car));
		exec.execute(new WaxOff(car));
		TimeUnit.SECONDS.sleep(5);
		exec.shutdownNow();
	}
}

运行结果:线程打断操作,随机结束线程!



全部评论

相关推荐

科大讯飞消费者bg二级研究院 语音算法岗 24k*14
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务