Lock interface

Posted by roice on Mon, 07 Mar 2022 04:39:50 +0100

catalogue

1.1 review synchronized

1.2 Lock interface

1.3 Lock method

1.4 difference between the two

1.1 review synchronized

It is a keyword of Java. It is a kind of synchronous lock, which can modify an object, variable and method,

To control this modified, sequential access,

Multithreaded programming steps:

First: create a resource class, attribute and operation method

Second: create multithreading and call the operation methods in the class

Combined with synchronized lock and multithreaded programming steps to realize the function of ticket selling: (high cohesion and low coupling)

package Lock;
//Multithreading realizes the function of selling tickets. synchronized mode
 class Ticket{ //Step 1 resource ticket
     private int num =30; //Define the number of tickets
     public synchronized void sale(){  //synchronized
         //Lock this resource to prevent multithreading errors
           //Resource operation and ticket selling method
         if(num>0){
             System.out.println(Thread.currentThread().getName()+
                     " Sold: 1 Zhang is still left"+(num--)); }
     }
 }
 
public class SaleTicket {
     //The second step is to create multiple threads and call the operation methods of the resource class
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        Thread t1 = new Thread(new Runnable() {
            @Override  //The specific method to create a thread is new Thread(new Runnable({override run method}, thread name)
            public void run() {
                for(int i =0; i<10;i++){
                    ticket.sale();
                }
            }
        } ,"t1"
        );
        t1.start();
        Thread t2= new Thread(
          Thread t2= new Thread(  //Lambda expression
                () ->{ for (int i = 0; i < 10; i++) {
                        ticket.sale();
                    } } ,"t2"
        );
        t2.start();
       
    }
}

When the code is executed, the execution of t1 and t2 threads are stacked together. This is because different threads and different objects start execution and can be accessed

1.2 Lock interface


Different from the built-in synchronization and monitor, LOCK is a class that can realize synchronous access through classes, and multiple interfaces realize classes: reentrant LOCK, etc

The programming steps of lock are the same as those of synchronized

Code definition of reentrant lock private final ReentrantLock lock = new ReentrantLock(true);
Lock lock();
Unlock lock unlock();
If the code in locking and unlocking is abnormal, the unlocking will not be executed, so it is best to add try finally

//The first step is to create a resource class and define attributes and operation methods
class LTicket {
    private int num = 30; //Number of tickets
    private final ReentrantLock lock = new ReentrantLock(true);  //Create a reentrant lock
    public void sale() {   //Ticket selling method
        //Lock
        lock.lock();
        try {
            if(number > 0) { //Judge whether there are tickets
                System.out.println(Thread.currentThread().getName()+" : 1 sold, remaining:"+(num--));
            }
        } finally {
            //Unlock
            lock.unlock();
        }
    }
}
 
public class LSaleTicket {
    //The second step is to create multiple threads and call the operation methods of the resource class
    //Create three threads
    public static void main(String[] args) {
        LTicket ticket = new LTicket();
 
new Thread(()-> {
    for (int i = 0; i < 40; i++) {
        ticket.sale();
    }
},"AA").start();
 
        new Thread(()-> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        },"BB").start();
 
        new Thread(()-> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        },"CC").start();
    }
}
 

1.3 Lock method

lock common interface

public interface Lock {
	void lock();
	void lockInterruptibly() throws InterruptedException;
	boolean tryLock();
	boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
	void unlock();
	Condition newCondition();
}

The lock() method is used to obtain the lock

  • Wait if the lock has been acquired by another thread
  • If an exception occurs, it will not be unlocked automatically. It needs to be done in the try{}catch {} block
lock.lock();
try{
	//Processing tasks
}catch(Exception ex){
}finally{
	lock.unlock(); //Release lock
}
 

The Condition class can also implement the wait / notify mode

The keyword synchronized can be used together with wait()/notify() to implement the wait / notify mode. The newcondition() method of Lock returns the Condition object. The Condition class can also implement the wait / notify mode

 

When notifying with notify(), the JVM will wake up a waiting thread randomly. You can use the Condition class for selective notification. There are two commonly used methods of Condition:

   1. await() will make the current thread wait and release the lock. When other threads call signal(), the thread will regain the lock and continue to execute
   2. signal() is used to wake up a waiting thread

ReentrantLock is the only class that implements the Lock interface, and ReentrantLock provides more methods
ReentrantLock reentrant lock

Reentrant ReadWriteLock provides many rich methods, but there are two main methods: readLock() and writeLock() to obtain read and write locks
writeLock(); To get the read lock
readLock(); Get write lock

public interface ReadWriteLock {
 Lock readLock();
 Lock writeLock();
}

1.4 difference between the two


Similarities and differences between synchronized and synchronized:

   1. synchronized is a java keyword, built-in, but lock is not built-in. It is a class that can realize synchronous access

And it is richer than the methods in synchronized
    2.synchronized will not release the lock manually, but lock needs to release the lock manually (deadlock will occur if it is not unlocked, and the lock needs to be released in the finally block)
   3. The lock thread waiting for the lock will be interrupted accordingly, while the synchronized thread will not. It will only wait all the time
   4. Through Lock, you can know whether you have successfully obtained the Lock, but synchronized cannot
   5. Lock can improve the efficiency of reading operations by multiple threads (when multiple threads compete)

Topics: JUC