1. 程式人生 > >java多執行緒哲學家思考吃飯問題

java多執行緒哲學家思考吃飯問題

package test;

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


public class Test{	
	static Scanner sc = new Scanner(System.in);
	static String line;
	
	static class chopsticks{
		boolean ishold = false;
		public synchronized void take(){
			while(ishold){
				try {
					wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			ishold = true;
		}
		
		synchronized void drop(){			
			ishold = false;
			notifyAll();
		}
	}
	
	static class thinker extends Thread{
		static int id = 0;
		int mid = id++;
		chopsticks left;
		chopsticks right;
		public thinker(chopsticks l,chopsticks r) {
			left = l;
			right = r;		
		}
		
		@Override
		public void run() {
			while(!interrupted()){
				System.out.println("哲學家"+mid+"思考");
				left.take();
				right.take();
				System.out.println("哲學家"+mid+"吃飯");
				left.drop();
				right.drop();
			}
		}
	}
	
	public static void main(String[] args) {		
		chopsticks[] cs = new chopsticks[10];
		for(int i=0;i<10;i++){
			cs[i] = new chopsticks();
		}
		
		for(int i=0;i<10;i++){
			new thinker(cs[i], cs[(i+1)%10]).start();;
		}
	}	
}