哲学家就餐

来源:java编程思想

是指两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。

产生死锁的四个必要条件
1) 互斥条件:一个资源每次只能被一个进程使用。
2) 占有且等待:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
3)不可强行占有:进程已获得的资源,在末使用完之前,不能强行剥夺。
4循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。

筷子类(资源类)

package com.thread;

public class Chopstick {
	private boolean taken=false;
	
	public synchronized void take() throws InterruptedException{
		while(taken==true){
			wait();
		}
		taken=true;
	}
	
	public synchronized void drop(){
		taken=false;
		notifyAll();
	}
}
哲学家类(线程类)

package com.thread;

import java.util.concurrent.TimeUnit;

public class Philosopher implements Runnable{
	private Chopstick left;
	private Chopstick right;
	private int id;
	public Philosopher(Chopstick left,Chopstick right, int id){
		this.left=left;
		this.right=right;
		this.id=id;
	}
	public void run(){
		try{
			while(!Thread.interrupted()){
				System.out.println(this+" thinking");
				TimeUnit.MILLISECONDS.sleep(0);
				
				left.take();
				System.out.println(this+" get left");
				right.take();
				System.out.println(this+" get right");
				System.out.println(this+" eating");
				
				left.drop();
				right.drop();
			}
		}catch(InterruptedException e){
			System.out.println(this+" interrupted");
		}
	}
	
	public String toString(){
		return "Philosopher "+id;
	}
}

死锁版本(每个哲学家都先取自己左边的筷子,后取自己右边的筷子,就有可能大家都拿到左筷子等待右筷子,造成循环等待)

package com.thread;

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

public class DeadLockingPhilosopher {
	public static void main(String[] args) throws InterruptedException{
		int size=10;
		Chopstick[] chopsticks=new Chopstick[size];
		for(int i=0;i<size;i++){
			chopsticks[i]=new Chopstick();
		}
		
		ExecutorService exec=Executors.newCachedThreadPool();
		for(int i=0;i<size;i++){
			exec.execute(new Philosopher(chopsticks[i],chopsticks[(i+1)%size],i));
		}
		
		TimeUnit.SECONDS.sleep(3);
	}
}

非死锁版本(破除循环等待,只要有一个哲学家先取右筷子,后取左筷子)

package com.thread;

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

public class NoDeadLockingPhilosopher {
	public static void main(String[] args) throws InterruptedException{
		int size=10;
		Chopstick[] chopsticks=new Chopstick[size];
		for(int i=0;i<size;i++){
			chopsticks[i]=new Chopstick();
		}
		
		ExecutorService exec=Executors.newCachedThreadPool();
		for(int i=0;i<size;i++){
			if(i<size-1){
				exec.execute(new Philosopher(chopsticks[i],chopsticks[i+1],i));
			}else{
				exec.execute(new Philosopher(chopsticks[0],chopsticks[i],i));
			}
		}
		
		TimeUnit.SECONDS.sleep(3);	
	}
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值