/*
 * This File is one of the examples from Java Application Development
 * Do not reproduce this code for others or use it in a commercial setting without prior permission from the author.
 */
package deadlock;

import tasks.TakeABreak;

/**
 *
 * @author Matthew Gregory
 * @website www.matthewgregory-author.com.au
 *
 */
public class Task2 implements Runnable {

    //This task requires two shared resources
    SharedResource1 res1;
    SharedResource2 res2;
    
    //The constructor will pass in the resources required
    public Task2(SharedResource1 res1,SharedResource2 res2){
        this.res1=res1;
        this.res2=res2;
    }

    public void run() {
        System.out.println(Thread.currentThread().getName()
                           +" is waiting to acquire a Lock on second resourse.");
        synchronized (res2) {//get a lock on second resource
            System.out.println(Thread.currentThread().getName()
                           +" acquired lock on second resourse.");
            TakeABreak.sleep();
            System.out.println(Thread.currentThread().getName()
                               +" is waiting to acquire a Lock on first resourse.");
            synchronized (res1) {//get a lock on first resource
                System.out.println(Thread.currentThread().getName()
                           +" acquired lock on first resourse.");
            }
            System.out.println(Thread.currentThread().getName()
                               +" released lock on first resourse.");
        }
        System.out.println(Thread.currentThread().getName()
                           +" released lock on second resourse.");
    }
}
