哲学家吃饭问题(资源加锁和超时释放)
2017-08-22 10:15
239 查看
public class Resourcelocking extends Thread{ private static int[] chopstick = { 1, 1, 1, 1, 1 }; private int i; public Resourcelocking(int i) { this.i = i; } @Override public void run() { //synchronized (chopstick) { //若注释此行,打开下行,不同步,5个per只拿到左筷子 { eat(this.getName()); //得到线程的名字 think(this.getName()); } } private void think(String name) { //在思考的时候把筷子置为可用 chopstick[i] = 1; chopstick[(i + 1) % 5] = 1; System.out.println("per"+name+" is thinking..."); } private void eat(String string) { while (true) { if (chopstick[i] != 0) {//说明当前现这根筷子没有被占用 chopstick[i]--; System.out.println("per" + this.getName() + " got left chopstick."); break; } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //拿到左筷子后开始拿右筷子 while (true) { if (chopstick[(i + 1) % 5] != 0) { chopstick[(i + 1) % 5]--; System.out.println("per" + this.getName() + " got right chopstick."); break; } } System.out.println("per" + string + " is eating..."); } }
public class Timeoutrelease extends Thread{
private static int[] chopstick = {1,1,1,1,1};
private int i;
private int n = 5;
public Timeoutrelease(int i) {
this.i = i;
}
@Override
public void run() {
//拿左筷子
synchronized (chopstick) {
while (chopstick[i] == 0) {
try {
chopstick.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
chopstick[i]--;
System.out.println("per" + this.getName()
+ " got left chopstick.");
chopstick.notify();
}
// 睡一下产生死锁
try {
Thread.sleep((long) (Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
//拿右筷子
synchronized (chopstick) {
while (chopstick[(i + 1) % n] == 0) {
try {
chopstick.wait(3*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
System.out.println(this.getName()+" waited 3s ,free left chopstick");
chopstick[i] ++;
}
}
chopstick[(i + 1) % n]--;
System.out.println("per" + this.getName()
+ " got right chopstick.");
System.out.println("per" + this.getName() + " is eating...");
chopstick[i]++;
chopstick[(i + 1) % n]++;
System.out.println("per"+this.getName()+" is thinking...");
chopstick.notify();
}
}
}
相关文章推荐
- 使用HttpURLConnection时遇到的资源未释放的问题
- qt中关闭窗口资源释放问题
- 浅谈C#托管程序中的资源释放问题(ZT)
- ***套接字连接已中止。这可能是由于处理消息时出错或远程主机超过接收超时或者潜在的网络资源问题导致的
- 5位哲学家吃饭问题(算法描述)
- 插件apk推出,资源释放的问题
- [转载]修复IE8进程延迟关闭的问题 充分释放资源
- Apache HttpClient 资源释放、请求超时,导致线程池用光、内存不足
- 资源释放的问题
- 同一线程多次创建 的 线程资源释放问题在每个线程的一开始,用pthred_detach(pthread_self())来使自己detach掉
- JDBC:JDBC资源释放的细节问题
- 深究跨dll的资源分配和释放问题
- C# 导入excel数据,解决关闭excel后不能释放资源的问题
- NeBeans模块中关闭TopComponent之后资源无法释放问题
- 黑马程序员技术博客之哲学家吃饭问题
- 使用using关键字同时释放多个资源的问题
- 应用程序结束时的资源释放及线程问题
- cocos2dx中加载图片资源的方法,和从内存中获取已经加载的图片资源的方法 以及释放问题
- 调用Excel导出文件的两种方式,主要解决了资源释放的问题。
- as3 Loader 加载资源后内存泄露无法释放的问题。