哲学就餐问题

用java的信号量类解决哲学家问题。



package 哲学家就餐问题;

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

public class Test {
	private static Semaphore fork[] = new Semaphore[5];
	private static Semaphore room = new Semaphore(4);

	public static void philosopher(int i) throws InterruptedException {
		think(i);
		try {
			Thread.sleep(5);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			room.acquire();
			System.out.println(i + "准备吃东西");
			try {
				fork[i].acquire();
				System.out.println(i + "拿起筷子" + i);
				;
				try {
					fork[(i + 1) % 5].acquire();
					;
					System.out.println(i + "拿起筷子" + (i + 1) % 5);
					eat(i);
					Thread.sleep(5);
				} catch (InterruptedException e) {

				} finally {
					fork[(i + 1) % 5].release();
					System.out.println(i + "放下筷子" + (i + 1) % 5);
				}
			} catch (InterruptedException e) {

			} finally {
				fork[i].release();
				System.out.println(i + "放下筷子" + i);
			}

		} catch (InterruptedException e) {

		} finally {
			room.release();
			System.out.println(i + "停止吃东西");
		}

	}

	public static void eat(int i) {
		// TODO Auto-generated method stub
		System.out.println(i + "在吃东西");
	}

	public static void think(int i) {
		// TODO Auto-generated method stub
		System.out.println(i + "在思考");
	}

	public static class Philosopher implements Runnable {
		int count = 3;
		int id;

		Philosopher(int id) {
			this.id = id;

		}

		public void run() {
			while (count > 0) {
				try {
					philosopher(id);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				count--;
			}
		}
	}

	public static void main(String args[]) {
		fork[0] = new Semaphore(1);
		fork[1] = new Semaphore(1);
		fork[2] = new Semaphore(1);
		fork[3] = new Semaphore(1);
		fork[4] = new Semaphore(1);
		ExecutorService executor = Executors.newFixedThreadPool(5);
		executor.execute(new Philosopher(0));
		executor.execute(new Philosopher(1));
		executor.execute(new Philosopher(2));
		executor.execute(new Philosopher(3));
		executor.execute(new Philosopher(4));

		executor.shutdown();
	}

}


你可能感兴趣的:(哲学就餐问题)