题目
原文:
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 by
thread: [“ + 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---