javaLock interface details and example code


java Lock interface

java.util.concurrent.locks

Interface Lock

public interface Loce

The Loce implementation provides a wider range of locking operations than can be obtained using the synchronized methods and statements

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class IntegerDemo {
  public static void main(String[] args) {
    //  create 3 Thread object
    SellTicket st = new SellTicket();

    Thread t1 = new Thread(st, " window 1");
    Thread t2 = new Thread(st, " window 2");
    Thread t3 = new Thread(st, " window 3");

    //  Starting a thread
    t1.start();
    t2.start();
    t3.start();
  }
}

class SellTicket implements Runnable {
  private int ticket = 100;
  private Lock lock = new ReentrantLock();

  public void run() {
    while (true) {
      lock.lock();

      if (ticket > 0) {
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + " On sale " + (ticket--) + " Tickets. ");
      }

      lock.unlock();
    }
  }
}

Thank you for reading, I hope to help you, thank you for your support of this site!