算法-哲学家就餐-arbitrator solution

本文介绍了一个经典的并发控制问题——哲学家就餐问题,并提供了一个使用Java实现的解决方案。通过使用同步和等待通知机制,确保了哲学家们在共享有限资源(餐叉)时不会发生死锁。同时,展示了如何使用线程池来模拟多个哲学家思考和进餐的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.mzs.demo4;

public class Fork {
	
	private boolean[] forks = new boolean[] {false, false, false, false, false};
	private int size = forks.length;
	
	public synchronized void take(int id) throws InterruptedException {
		while (forks[id % size] || forks[(id + 1) % size]) {
			wait();
		}
		forks[id % size] = true;
		forks[(id + 1) % size] = true;
	}
	
	public synchronized void put(int id) {
		forks[id % size] = false;
		forks[(id + 1) % size] = false;
		notifyAll();
	}

}

 

package com.mzs.demo4;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;

public class Philosopher implements Runnable {
	
	private int id;
	private Fork fork;

	public Philosopher(int id, Fork fork) {
		this.id = id;
		this.fork = fork;
	}
	
	@Override
	public void run() {
		while (true) {
			try {
				think();
				fork.take(id);
				eat();
				fork.put(id);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	private void think() {
		int time = (int) (Math.max(0.5, ThreadLocalRandom.current().nextDouble(1)) * 2000);
		System.out.println("I am philosopher " + id + ", and I am thinking for " + time + " milliseconds");
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private void eat() {
		int time = (int) (Math.max(0.5, ThreadLocalRandom.current().nextDouble(1)) * 2000);
		System.out.println("I am philosopher " + id + ", and I am eating for " + time + " milliseconds");
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		ExecutorService service = Executors.newFixedThreadPool(5);
		Fork fork = new Fork();
		for (int i = 0; i < 5; i++) {
			Runnable runnable = new Philosopher(i, fork);
			service.execute(runnable);
		}
		service.shutdown();
	}
	
	
	

}

详细内容可看:https://blog.youkuaiyun.com/Dylan_Frank/article/details/80052565

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值