Cracking the coding interview--Q18.4

本文介绍如何设计一个类,提供锁机制,确保程序运行过程中不出现死锁情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

原文:

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---


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值