java 并发学习笔记(三)哲学家就餐

package philosophers;

//Chopsticks for dining philosophers
public class Chopstick {
	private boolean taken=false;
	public synchronized void take() throws InterruptedException
	{
		while(taken)
		{
			wait();
		}
		taken=true;
	}
	
	public synchronized void drop(){
		taken=false;
		notifyAll();
	}
}
package philosophers;

import java.util.Random;
import java.util.concurrent.TimeUnit;

//A dining philosopher
public class Philosopher implements Runnable{
	private Chopstick left;
	private Chopstick right;
	private final int id;
	private final int ponderFactor;
	private Random rand=new Random(47);
	
	private void pause() throws InterruptedException 
	{
		if(ponderFactor==0)
		{
			return ;
		}
		TimeUnit.MILLISECONDS.sleep(1000);
	}
	
	public Philosopher(Chopstick left,Chopstick right,int ident,int ponder)
	{
		this.left=left;
		this.right=right;
		id=ident;
		ponderFactor=ponder;
	}

	public void run() {
		try {
			while(!Thread.interrupted())
			{
				System.out.println(this + " "+ "thinking");
				pause();
				//Philosopher becomes hungry
				System.out.println(this + " "+ "grabbing right");
				right.take();
				System.out.println(this + " "+ "grabbing left");
				left.take();
				System.out.println(this + " "+ "eating");
				pause();
				right.drop();
				left.drop();
			}
		} catch (InterruptedException e) {
			//e.printStackTrace();
			System.out.println(this + " "+ "exiting via interrupt");
		}
	}
	
	public String toString()
	{
		return "Philosopher "+id;
	}
}
package philosophers;

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

public class TextPhilosophers {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{

		int ponder=5;
		int size=5;
		
		ExecutorService exec=Executors.newCachedThreadPool();
		Chopstick[] sticks=new Chopstick[size];
		for(int i=0;i<size;i++)
		{
			sticks[i]=new Chopstick();
		}
		for(int i=0;i<size;i++)
		{
			if(i<(size-1))
			{
				exec.execute(new Philosopher(sticks[i],sticks[i+1],i,ponder));
			}
			else
			{
				//这里是通过将最后一个Philosopher先拿起和放下左边的Chopstick,来移除死锁
				exec.execute(new Philosopher(sticks[0],sticks[i],i,ponder));
			}
		}
		System.out.println("Press 'Enter' to quit");
		System.in.read();
		
		exec.shutdownNow();
	}

}


   在这里处理死锁的方法是通过破坏循环等待

你可能感兴趣的:(java,thread)