操作系统线程同步之哲学家进餐问题

1、问题描述(死锁)

五个哲学家,五只筷子,只有获得一双筷子之后才能就餐,就有可能出现这种情况:每个哲学家都获得了一只筷子,卡死在那个地方。
在这里插入图片描述

2、解决哲学家就餐问题当然后很多方法:

(1)有一个服务生来负责避免死锁
(2)哲学家在拿筷子的时候,确保左右都有筷子才同时拿起左右两只筷子
(3)规定拿筷子的方式:给筷子编号,先拿号码小的筷子

3、第二种方式java代码实现:

class Chopsticks {
public static List<Boolean> chops = new ArrayList<Boolean>();
static {
chops.add(false); //为了方便计算,第一个不会参与计算
chops.add(false);
chops.add(false);
chops.add(false);
chops.add(false);
}

public synchronized void getChop() {
	String currentName = Thread.currentThread().getName();
	int index = Integer.parseInt(currentName);
	while (chops.get(index) || chops.get((index + 1)%5)) {
		try {
			wait();
		} catch (InterruptedException e) {
			e.printStackTrace();
 		 }
	}
	chops.set(index, true);
	chops.set((index + 1)%5 ,true);
}

public synchronized void freeChop() {
	String currentName = Thread.currentThread().getName();
	int index = Integer.parseInt(currentName);
	chops.set(index, false);
	chops.set((index + 1)%5 ,false);
	notifyAll();
}

class PhilosopherThread extends Thread {
private String name; //线程名称,给哲学家编序号用
private Chopsticks chopsticks;

public PhilosopherThread (String name, Chopsticks chopsticks) {
	super(name);
	// this.name = name;
	this.chopsticks = chopsticks;
}

@Override
public void run() {
	while (true) {
		chopsticks.getChop();
		System.out.println(Chopsticks.chops);
		this.eat();
		chopsticks.freeChop();
	}
}

public void eat() {
	try {
		Thread.sleep(1000);
	} catch (InterruptedException e) {
	e.printStackTrace();
		}
	}
}

public class PhilosopherTest {
	public static void main(String[] args) {
	Chopsticks chopsticks = new Chopsticks();
	PhilosopherThread philosopherThread1 = new PhilosopherThread("0", chopsticks);
	PhilosopherThread philosopherThread2 = new PhilosopherThread("1", chopsticks);
	PhilosopherThread philosopherThread3 = new PhilosopherThread("2", chopsticks);
	PhilosopherThread philosopherThread4 = new PhilosopherThread("3", chopsticks);
	PhilosopherThread philosopherThread5 = new PhilosopherThread("4", chopsticks);

	philosopherThread1.start();
	philosopherThread2.start();
	philosopherThread3.start();
	philosopherThread4.start();
	philosopherThread5.start();
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值