Skip to content

Latest commit

 

History

History
59 lines (44 loc) · 1.47 KB

File metadata and controls

59 lines (44 loc) · 1.47 KB

Locks

  • Alternative to using synchronized to control access to a shared resources.
  • Lock is acquired before before accessing a shared resource. when done with the resource the lock is released.
  • If second thread tries to acquire the lock when it is in use by first thread, the thread will suspend until the lock is released.
import java.util.concurrent.locks.ReentrantLock;


class Counter {
    static int counter;
}

class Task implements Runnable {
    ReentrantLock lk;

    Task(ReentrantLock lk) {
        this.lk = lk;
    }

    /**
     * Runs this operation.
     */
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println("Starting " +  name);
        try {
            System.out.println(name + " is waiting to lock count");
            this.lk.lock();
            Counter.counter++;
            System.out.println(name + ", counter: " + Counter.counter);
            System.out.println(name + " is sleeping");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println(name + ">> interrupted");
        }finally {
            System.out.println(name + " is unlocking count");
            this.lk.unlock();
        }
    }
}


public class Main {

    public static void main(String[] args) {
        ReentrantLock lk = new ReentrantLock();

        new Thread(new Task(lk), "thread1").start();
        new Thread(new Task(lk), "thread2").start();


    }
}