Cracking the coding interview--Q18.4
来源:互联网 发布:广发淘宝卡不送集分宝 编辑:程序博客网 时间:2024/06/03 12:32
题目
原文:
Design a class which provides a lock only if there are no possible deadlocks.
译文:
设计一个提供锁但不可能发生死锁的类。
解答
原书解答:
class MyThread extends Thread {long time;ArrayList<Resource> res = new ArrayList<Resource>();public ArrayList<Resource> getRes() { return res; }public void run() {/* Run infinitely */time = System.currentTimeMillis();int count = 0;while (true) {if (count < 4) {if (Question.canAcquireResource(this,Question.r[count])) {res.add(Question.r[count]);count++;System.out.println(“Resource: [“ +Question.r[count - 1].getId() + “] acquired bythread: [“ + this.getName() + “]”);try {sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}else {this.stop();}}}public long getTime() { return time; }public void setRes(ArrayList<Resource> res) { this.res = res; MyThread(String name) {super(name);}}
死锁例子:
/*死锁同步中嵌套同步,而锁不同*/class Ticket implements Runnable{private int tick=100; Object obj=new Object();boolean flag=true;public void run(){if(flag){while(true){synchronized(Ticket.class){ //若是obj,会出现0号票if(tick>0){System.out.println(currentThread().getName()+"sale:"+tick--);}}}}else{while(true) show();}}public static synchronized void show(){synchronized(obj){if(tick>0){try{Thread.sleep(10);}catch(Exception e){System.out.println(currentThread().getName()+"sale:"+tick--);}}}}class DeadLockDemo{public static void main(String[] args){Ticket t=new Ticket();Thread t1=new Thread(t);Thread t2=new Thread(t);Thread t3=new Thread(t);Thread t4=new Thread(t);t1.start();t2.start();t3.start();t4.start();}}
---EOF---
0 0
- Cracking the coding interview--Q18.4
- Cracking the coding interview--Q18.1
- Cracking the coding interview--Q18.2
- Cracking the coding interview--Q18.3
- Cracking the coding interview--Q18.5
- Cracking the coding interview--Q18.6
- Cracking the Coding Interview
- 《Cracking the coding interview》
- Cracking The Coding Interview
- Cracking the coding interview
- Cracking the coding interview
- Cracking the coding interview--Q12.4
- Cracking the Coding Interview Chap1 Q1.4
- Cracking the coding interview--Q1.4
- Cracking the coding interview--Q2.4
- Cracking the coding interview--Q3.4
- Cracking the coding interview--Q1.4
- Cracking the coding interview--Q2.4
- SQL SERVER中XML查询:FOR XML指定AUTO
- 啊事干呗SRHN
- 如何使用Docker搭建私有的DNSServer
- 大头鬼没开始日语课,
- 验证字符串中是否存在html标签
- Cracking the coding interview--Q18.4
- HDU 2838 Cow Sorting
- 开源erp
- ant构建javaWar包xml模板
- hdu 3625 第一类斯特灵数
- PHP5+APACHE2.2配置
- ACM第一课---数论之欧拉函数
- hibernate结束session的四个独立步骤
- apache设置mpm_winnt_module模块