アルゴリズム-哲学者食事-アルビトレートソロ


package com.mzs.demo4;

public class Fork {
	
	private boolean[] forks = new boolean[] {false, false, false, false, false};
	private int size = forks.length;
	
	public synchronized void take(int id) throws InterruptedException {
		while (forks[id % size] || forks[(id + 1) % size]) {
			wait();
		}
		forks[id % size] = true;
		forks[(id + 1) % size] = true;
	}
	
	public synchronized void put(int id) {
		forks[id % size] = false;
		forks[(id + 1) % size] = false;
		notifyAll();
	}

}
 
package com.mzs.demo4;

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

public class Philosopher implements Runnable {
	
	private int id;
	private Fork fork;

	public Philosopher(int id, Fork fork) {
		this.id = id;
		this.fork = fork;
	}
	
	@Override
	public void run() {
		while (true) {
			try {
				think();
				fork.take(id);
				eat();
				fork.put(id);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	private void think() {
		int time = (int) (Math.max(0.5, ThreadLocalRandom.current().nextDouble(1)) * 2000);
		System.out.println("I am philosopher " + id + ", and I am thinking for " + time + " milliseconds");
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private void eat() {
		int time = (int) (Math.max(0.5, ThreadLocalRandom.current().nextDouble(1)) * 2000);
		System.out.println("I am philosopher " + id + ", and I am eating for " + time + " milliseconds");
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		ExecutorService service = Executors.newFixedThreadPool(5);
		Fork fork = new Fork();
		for (int i = 0; i < 5; i++) {
			Runnable runnable = new Philosopher(i, fork);
			service.execute(runnable);
		}
		service.shutdown();
	}
	
	
	

}
詳細はご覧ください.https://blog.csdn.net/Dylan_Frank/articale/detail/8005625