CareerCup 16.3 Philosopher Dinner -- DeadLock, Synchronized


package CareerCup;

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

class Chopstick {
	private Lock lock;
	Chopstick() {
		lock = new ReentrantLock();
	}
	public boolean pickUp() {
		return lock.tryLock();
	}
	
	public void putDown() {
		lock.unlock();
	}
}

class Philosopher extends Thread{
	private Chopstick left;
	private Chopstick right;
	int bites = 3;
	private String name;
	
	Philosopher(Chopstick l, Chopstick r, String n) {
		this.left = l;
		this.right = r;
		name = n;
	}
	
	public boolean eat() {
		if(!left.pickUp()) {
			return false;
		}
		if(!right.pickUp()) {
			left.putDown();
			return false;
		}
		chew();
		left.putDown();
		right.putDown();
		
		return true;
	}
	
	void chew() {
		for(int i = 1; i <= bites; i++)
			System.out.println(name + " is chewing " + i + "th bite");
	}
	
	public void run() {
		eat();
	}
	
}

public class PhilosopherDinner {
	
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Chopstick sticks[] = new Chopstick[3];
		Philosopher phis[] = new Philosopher[3];

		for(int j = 0; j < sticks.length; j++) 
			sticks[j] = new Chopstick();
		
		for(int i = 0; i < phis.length; i++) {
			if(0 == i) {
				phis[i] = new Philosopher(sticks[sticks.length - 1], sticks[0], 0 + "");
			} 
			else {
				phis[i] = new Philosopher(sticks[i - 1], sticks[i], i + "");
			}
		}
		
		for(Philosopher p : phis) {
			p.start();
		}
		

	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值