廢話不多說,代碼開始:
- public class Scientist extends Thread {
- /*
- * @author:Bore
- * @mail:[email protected]
- * @time:2010/12/7
- * 1.哲學家進餐,5個哲學家,5只筷子
- * 2.哲學家通過getChopsticks()方法,來取筷子。
- * 3.當哲學家同時獲得左邊和右邊兩隻筷子後纔可以進餐。否則把已經得到的筷子也釋放
- * 4.如果一直筷子也沒有,進程阻塞,等待其他哲學家釋放資源
- * 5.進程後,釋放已經獲得的資源
- */
- static byte[] chopsticks={1,1,1,1,1};//五隻筷子
- public Scientist(String name){
- super(name);
- }
- public void run() {
- getChopsticks();
- }
- public void getChopsticks(){//開始搶筷子
- int tem=Integer.parseInt(this.getName().substring(3));//獲取哲學家編號
- if(tem==0){//如果是第一位科學家,先搶左邊的筷子
- if(leftChopsticks(tem)){//如何獲取了左邊的筷子
- if(rightChopsticks(tem)){//如果獲取了右邊的筷子
- eating();//開始吃飯
- freeLeftChopsticks(tem);//釋放左邊筷子
- freeRightChopsticks(tem);//釋放右邊筷子
- }else{
- freeLeftChopsticks(tem);
- System.out.println("由於"+this.getName()+"無法獲得右手邊的筷子,所以他把已獲得的左手的筷子也釋放了!");
- try {
- this.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- getChopsticks();
- }
- }else{
- System.out.println(this.getName()+"暫時無法獲取兩隻筷子,準備休眠!");
- try {
- this.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- getChopsticks();
- }
- }else{//其他情況先搶右邊的筷子
- if(rightChopsticks(tem)){//先搶右手邊的筷子。
- if(leftChopsticks(tem)){//如果獲得了右手邊的。去搶左手邊的筷子。
- eating();//如果獲得了兩隻筷子,開始吃飯
- freeLeftChopsticks(tem);//吃完了。釋放左手邊的筷子
- freeRightChopsticks(tem);//釋放右手邊的筷子
- }else{
- freeRightChopsticks(tem);
- System.out.println("由於"+this.getName()+"無法獲得左手邊的筷子,所以他把已獲得的右手的筷子也釋放了!");
- try {
- this.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- getChopsticks();
- }
- }else{
- System.out.println(this.getName()+"暫時無法獲取兩隻筷子,準備休眠!");
- try {
- this.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- getChopsticks();
- }
- }
- }
- public boolean leftChopsticks(int tem){//獲取左手邊筷子
- if(chopsticks[tem]==1){
- chopsticks[tem]=0;
- System.out.println(this.getName()+"左手邊筷子已獲得!");
- return true;
- }else{
- System.out.println(this.getName()+"左手邊筷子已被哲學家"+(tem-1)+"搶走!");
- return false;
- }
- }
- public boolean rightChopsticks(int tem){//獲取右手邊筷子
- int i=(tem+1)%5;
- if(chopsticks[i]==1){
- chopsticks[i]=0;
- System.out.println(this.getName()+"右手邊筷子已獲得!");
- return true;
- }else{
- System.out.println(this.getName()+"右手邊筷子已被哲學家"+i+"搶走!");
- return false;
- }
- }
- public void freeLeftChopsticks(int tem){//獲取左手邊筷子
- chopsticks[tem]=1;
- System.out.println(this.getName()+"左手邊筷子已釋放!");
- }
- public void freeRightChopsticks(int tem){//獲取右手邊筷子
- int i=(tem+1)%5;
- chopsticks[i]=1;
- System.out.println(this.getName()+"右手邊筷子已釋放!");
- }
- public void eating(){//開始進餐
- System.out.println("*"+this.getName()+"兩隻手都有了筷子,所以開始吃飯!");
- }
- /**
- * 主函數
- */
- public static void main(String[] args) {
- for(int i=0; i<5; i++){
- new Scientist("哲學家"+i).start();
- }
- }
- }