package threadsexample;
/*内容描述:此为哲学家进餐问题————有四支筷子,四个哲学家,一边吃饭一边思考,任何时刻,只能有两个人吃饭,两个人思考的多线程问题*/
public class TotalThread {
public static void main(String [] args)
{
final ChopStick[] chopsticks=new ChopStick[4];//四根筷子
final Philosopher[] philosophers=new Philosopher[3];//3个哲学家
for(int i=0;i<4;i++)
{
chopsticks[i]=new ChopStick();
}
for(int i=0;i<3;i++)
{
philosophers[i]=new Philosopher(chopsticks[i],chopsticks[(i+1)%4],i);
}
for(int i=0;i<3;i++)
{
philosophers[i].start();
}
}
}
/*定义筷子资源___拿起和放弃*/
class ChopStick
{
boolean available;//筷子数量
ChopStick()
{
available=true;//让第一个哲学家先使用筷子
}
public synchronized void takeup()
{//定义共享方法
while(!available)
{
try
{
System.out.println("哲学家等待另一支筷子");
wait();//得不到资源的情况下,主动放弃资源的控制,进入等待状态
}catch(Exception e)
{
e.printStackTrace();
}
}
available=false;
}
public synchronized void putdown()
{
//定义放下筷子共享资源
//放下筷子是思考,拿起筷子是吃饭或等待另一只筷子
available=true;
notify();//当前资源已经执行完毕,放弃对资源的控制,通知其他线程恢复执行
}
}
class Philosopher extends Thread{
//定义哲学家思考问题
ChopStick left,right;//定义两支筷子
int phio_num;
public Philosopher(ChopStick left,ChopStick right,int phio_num)
{
this.left=left;
this.right=right;
this.phio_num=phio_num;
}
public void eat()
{//吃饭过程
left.takeup();
right.takeup();
System.out.println("哲学家:"+(this.phio_num+1)+"在用餐");
}
public void think()
{//定义思考
left.putdown();
right.putdown();
System.out.println("哲学家:"+(this.phio_num+1)+"在思考");
}
public void run()
{
//定义线程执行体
while(true)
{
eat();
try
{
sleep(1000);
}catch(Exception e)
{
e.printStackTrace();
}
think();
try
{
sleep(1000);
}catch (Exception r)
{r.printStackTrace();}
}
}
}