喫飯的哲學家(線程死鎖例子)

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 > 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 < 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 < 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 > 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);

}

 

}

 

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章