27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 18 | Threads <strong>and</strong> Locks<br />

18.4 Design a class which provides a lock only if <strong>the</strong>re are no possible deadlocks.<br />

pg 86<br />

SOLUTION<br />

For our solution, we implement a wait / die deadlock prevention scheme.<br />

1 class MyThread extends Thread {<br />

2 long time;<br />

3 ArrayList res = new ArrayList();<br />

4 public ArrayList getRes() { return res; }<br />

5<br />

6 public void run() {<br />

7 /* Run infinitely */<br />

8 time = System.currentTimeMillis();<br />

9 int count = 0;<br />

10 while (true) {<br />

11 if (count < 4) {<br />

12 if (Question.canAcquireResource(this,<br />

13 Question.r[count])) {<br />

14 res.add(Question.r[count]);<br />

15 count++;<br />

16 System.out.println(“Resource: [“ +<br />

17 Question.r[count - 1].getId() + “] acquired by<br />

18 thread: [“ + this.getName() + “]”);<br />

19 try {<br />

20 sleep(1000);<br />

21 } catch (InterruptedException e) {<br />

22 e.printStackTrace();<br />

23 }<br />

24 }<br />

25 }<br />

26 else {<br />

27 this.stop();<br />

28 }<br />

29 }<br />

30 }<br />

31<br />

32 public long getTime() { return time; }<br />

33 public void setRes(ArrayList res) { this.res = res; }<br />

34 MyThread(String name) {<br />

35 super(name);<br />

36 }<br />

37 }<br />

2 6 1<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Knowledge Based

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!