java 并发学习笔记(三)哲学家就餐

本文探讨了经典的哲学家就餐问题,并通过Java代码实现了解决方案,有效地避免了死锁的发生。文章详细介绍了如何通过同步机制来确保哲学家们能够正确地使用筷子进行就餐。
package philosophers;

//Chopsticks for dining philosophers
public class Chopstick {
private boolean taken=false;
public synchronized void take() throws InterruptedException
{
while(taken)
{
wait();
}
taken=true;
}

public synchronized void drop(){
taken=false;
notifyAll();
}
}
package philosophers;

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

//A dining philosopher
public class Philosopher implements Runnable{
private Chopstick left;
private Chopstick right;
private final int id;
private final int ponderFactor;
private Random rand=new Random(47);

private void pause() throws InterruptedException
{
if(ponderFactor==0)
{
return ;
}
TimeUnit.MILLISECONDS.sleep(1000);
}

public Philosopher(Chopstick left,Chopstick right,int ident,int ponder)
{
this.left=left;
this.right=right;
id=ident;
ponderFactor=ponder;
}

public void run() {
try {
while(!Thread.interrupted())
{
System.out.println(this + " "+ "thinking");
pause();
//Philosopher becomes hungry
System.out.println(this + " "+ "grabbing right");
right.take();
System.out.println(this + " "+ "grabbing left");
left.take();
System.out.println(this + " "+ "eating");
pause();
right.drop();
left.drop();
}
} catch (InterruptedException e) {
//e.printStackTrace();
System.out.println(this + " "+ "exiting via interrupt");
}
}

public String toString()
{
return "Philosopher "+id;
}
}
package philosophers;

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

public class TextPhilosophers {

/**
* @param args
*/
public static void main(String[] args) throws Exception{

int ponder=5;
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++)
{
if(i<(size-1))
{
exec.execute(new Philosopher(sticks[i],sticks[i+1],i,ponder));
}
else
{
//这里是通过将最后一个Philosopher先拿起和放下左边的Chopstick,来移除死锁
exec.execute(new Philosopher(sticks[0],sticks[i],i,ponder));
}
}
System.out.println("Press 'Enter' to quit");
System.in.read();

exec.shutdownNow();
}

}


在这里处理死锁的方法是通过破坏循环等待
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值