Thinking in java 哲学家进食问题

DeadlockingDiningPhilosopher.java

哲学家围着圆桌坐下,左右各有一根筷子,需要同时拥有左右筷子才能进食。

筷子是共享资源,使用和释放资源需要加锁处理。如果所有的哲学界都是先取左边的筷子,就会导致每个哲学家都有一根筷子,等待自己右边的哲学家释放筷子,从而陷入死锁的状态。

package com.test.concurrent;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DeadlockingDiningPhilosopher {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		int ponder=10;
		int size=5;
		ExecutorService exec=Executors.newCachedThreadPool();
		ChopStick[] sticks=new ChopStick[size];
		for(int i=0;i<size;i++){
			sticks[i]=new ChopStick();
		}
		for(int i=0;i<size;i++){
			exec.execute(new Philosopher(sticks[i],sticks[(i+1)%size],i,ponder));
			//此处可以通过修改最后一个哲学家取筷子的顺序来避免死锁,最后一个反序取筷子
		}
		TimeUnit.SECONDS.sleep(5);
		exec.shutdownNow();
		System.out.println("total eat count:"+Philosopher.eatcount);
	}

}

class ChopStick{
	private boolean taken=false;
	public synchronized void take() throws InterruptedException{
		while(taken){
			wait();
		}
		taken=true;
	}
	public synchronized void drop(){
		taken=false;
		notifyAll();
	}
}
class Philosopher implements Runnable{
	public static int eatcount=0;
	private ChopStick left;
	private ChopStick right;
	private final int id;
	private final int ponderFactor;
	private Random rand=new Random(47);
	public Philosopher(ChopStick left,ChopStick right,int ident,int ponder){
		id=ident;
		ponderFactor=ponder;
		this.left=left;
		this.right=right;
	}
	private void pause() throws InterruptedException{
		if(ponderFactor==0)
			return;
		TimeUnit.MILLISECONDS.sleep(rand.nextInt(ponderFactor*250));
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while(!Thread.interrupted()){
				System.out.println(this+"  "+"thinking   ");
				pause();
				
				System.out.print(this+"  grbbing right  ");
				right.take();
				
				System.out.print(this+"   grabbing left  ");
				left.take();
				
				System.out.println(this+" is eating!!!! ");
				eatcount++;
				right.drop();
				left.drop();
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public String toString(){
		return "Philosopher "+id;
	}
	
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值