6. Lock Lock synchronization

  • Prior to Java 5.0, the only mechanisms available to coordinate access to shared objects were synchronized and volatile. Some new mechanisms have been added since Java 5.0, but not as an alternative to built-in locks, but as an optional advanced feature when built-in locks are not available.
  • ReentrantLock implements the Lock interface and provides the same mutual exclusion and memory visibility as synchronized. However, it provides more flexibility in handling locks than synchronized.

6.1 a case

class Ticket implements Runnable {

    private int tick = 100;

    private Lock lock = new ReentrantLock();

    @Override
    public void run(a) {
        while(lock ! =null) {
            / / lock
            lock.lock();

            try {
                if (tick > 0) {
                    // Sleep, for display convenience
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "Completed ticket, remaining tickets are:"+ --tick); }}finally {
                / / releases the locklock.unlock(); }}}}Copy the code

test

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(ticket, "Window 1").start();
        new Thread(ticket, "Window 2").start();
        new Thread(ticket, "Window 3").start();
    }
Copy the code