Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ex;
- public class Deadlock implements Runnable {
- public static void main(String[] args) {
- Object a = "Resource A";
- Object b = "Resource B";
- Thread t1 = new Thread(new Deadlock(a, b));
- Thread t2 = new Thread(new Deadlock(a, b));
- t1.start();
- t2.start();
- }
- private Object firstResource;
- private Object secondResource;
- public Deadlock(Object first, Object second) {
- firstResource = first;
- secondResource = second;
- }
- @Override
- public void run() {
- while (true) {
- System.out.println(Thread.currentThread().getName() + " Looking for lock on " + firstResource);
- synchronized (firstResource) {
- System.out.println(Thread.currentThread().getName() + " Obtained lock on " + firstResource);
- System.out.println(Thread.currentThread().getName() + " Looking for lock on " + secondResource);
- }
- synchronized (secondResource) {
- System.out.println(Thread.currentThread().getName() + " Obtained lock on " + secondResource);
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement