---
title: "吃饭的哲学家（线程死锁例子）"
author: "Breese"
date: "2013-02-22T18:04:49Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-02-22T18:04:49Z"
id: 1812646
url: "https://breese.iteye.com/blog/1812646"
---

package tianya.cn.philopherfood;

 

public class Chopstick {

private static int count = 0;

private int number = count++;

 

public String toString(){

return "Chopstick" + number;

}

}

===========================================

package tianya.cn.philopherfood;

 

import java.util.Random;

 

public class Philosopher extends Thread {

private static Random random = new Random();

private static int count = 0;

 

private int number = count++;

 

private Chopstick leftChopstick;

private Chopstick rightChopstick;

 

public static int ponder = 0;//package access,time of philosopher thinking

 

public Philosopher(Chopstick left, Chopstick right){

leftChopstick = left;

rightChopstick = right;

start();

}

 

public void thinking(){

System.out.println();

 

if(ponder &gt; 0){

 

try {

sleep(random.nextInt(ponder));

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

 

public void eat(){

synchronized (leftChopstick) {

System.out.println(this + " has " + this.leftChopstick + " waitting for " + this.rightChopstick);

}

 

synchronized (rightChopstick) {

System.out.println(this + "eating");

}

}

 

 

public String toString(){

return "Philospher" + number;

}

 

public void run(){

while(true){

thinking();

eat();

}

}

}

 

==========================================================

package tianya.cn.main;

 

import java.util.Timer;

import java.util.TimerTask;

 

import tianya.cn.philopherfood.Chopstick;

import tianya.cn.philopherfood.Philosopher;

 

public class DiningPhilosophers {

 

/\**

\* @param args

\*/

public static void main(String\[] args) {

// TODO Auto-generated method stub

 

if( args.length &lt; 3){

System.err.println("输入参数错误！。。。。。。。");

System.exit(0);

}

 

Philosopher\[] philosopher = new Philosopher\[ Integer.parseInt(args\[0]) ];

 

Philosopher.ponder = Integer.parseInt( args\[1] );

 

Chopstick

left = new Chopstick(),

right = new Chopstick(),

first = left;

 

int i = 0;

if(i &lt; philosopher.length - 1){

philosopher\[i++] =  new Philosopher(left, right);

left = right;

right =  new Chopstick();

}

 

if(args\[2].equals("deadlock")){

 

philosopher\[i] = new Philosopher(left, first);

}else{

//swaping values prevents deadblock

philosopher\[i] = new Philosopher(first, left);

}

 

//

if(args.length &gt; 3){

int delay =  Integer.parseInt( args\[3] );

new Timer().schedule(new TimerTask() {

 

@Override

public void run() {

// TODO Auto-generated method stub

System.out.println("OVER!!!");

System.exit(0);

}

}, delay);

}

 

}

 

}