import java.util.concurrent.locks.ReentrantLock;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public class pc_locks {
    public   The_Store_l a_store=new The_Store_l(3500);
    public static long start_time=System.currentTimeMillis()/1000;
    public static long now(){
        return((System.currentTimeMillis()/1000)-start_time);
    }

    public static void main(String[] args) {     
        new pc_locks();
    }
    public pc_locks(){

        List<Consumer_l> list = new ArrayList<>();
        for (int i=0;i<5;i++) {
            list.add(new Consumer_l(a_store,i));
        }
        long start_time=System.currentTimeMillis()/1000;
        for (int i=0;i<5;i++) {
            list.get(i).start();
        }
        /* Consumer_l c1 = new Consumer_l(a_store,1);
         c1.start();*/
        try {
            /*Wait for the threads to finish
            /  c1.join();*/
            for (int i=0;i<5;i++) {
                list.get(i).join();
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println("All Consumers are Finished at " +pc_locks.now()+".");
    }
}

class The_Store_l extends ReentrantLock {
    int work_time;
    public The_Store_l(int wt){
        work_time=wt;
    }
    public  int use(int i) {
        System.out.println("Consumer "+i+" Work Begun on Shared Resource at " +pc_locks.now()+"sec .");
        try {
            Thread.sleep(work_time);
        } catch (InterruptedException e) {
        }
        System.out.println("Consumer "+i+" Work Finished on Shared Resource at " +pc_locks.now()+"sec .");
        return 1;
    }
}

class Consumer_l extends Thread {
    The_Store_l my_store;
    int my_number;
    int a_random (){
        return ThreadLocalRandom.current().nextInt(1000, 3001);
    }


    public Consumer_l(The_Store_l a_store,int i){  
        my_store=a_store;
        my_number=i;
    }
    public void run() {
        while (!my_store.tryLock()) {
            int this_random=a_random();
            try {

                Thread.sleep(this_random);
            } catch (InterruptedException e) {
            }
            System.out.println("    Consumer "+my_number+" tried lock at "+pc_locks.now()+
                               ". Not available, doing other work for "+this_random+"ms .");
        }
        my_store.use(my_number);
        my_store.unlock();
    }
}