环形死锁

package org.yangzlgg.thread.lock;

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

public class DeadLock {
	
	static class Chopstick{
		private boolean taken = false;
		public synchronized void take() throws InterruptedException{
			while(taken){
				wait();
			}
			taken = true;
		}
		
		public synchronized void drop(){
			taken = false;
			notifyAll();
		}
	}
	
	
	static 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{
			TimeUnit.MILLISECONDS.sleep(rand.nextInt(ponderFactor * 250));
		}
		
		public Philosopher(Chopstick left, Chopstick right, int id, int ponder){
			this.left = left;
			this.right = right;
			this.id = id;
			this.ponderFactor = ponder;
		}
		
		@Override
		public void run() {
			try{
				while(!Thread.interrupted()){
					//System.out.println(this+" thinking");
					//pause();
					right.take();
					System.out.println(this+" grabbing right");
					left.take();
					System.out.println(this+" grabbing left");
					//System.out.println(this+" eating");
					//pause();
					right.drop();
					left.drop();
					Thread.yield();
				}
			}catch(InterruptedException e){
				System.out.println(this +" "+"exiting via interrupt");
			}
		}
		
		@Override
		public String toString() {
			return "#"+this.id;
		}
	}
	
	static class Deadlock{
		public static void main(String[] args) {
			int ponder = 1;
			int size = 5;
			ExecutorService executorService = 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){
					executorService.execute(new Philosopher(sticks[i], sticks[i+1], i, ponder));					
				}else{
					executorService.execute(new Philosopher(sticks[0], sticks[i], i, ponder));
				}
			}
			
			executorService.shutdown();
		}
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值