Java Lock instance use

Java Lock instance use

synchronized和Lock区别:
synchronized:

(If a code block is modified by synchronized, when a thread acquires the corresponding lock and executes the code block, other threads can only wait forever, waiting for the thread that acquired the lock to release the lock) The
lock status of the thread that acquired the lock:

1. The thread that acquired the lock has finished executing the code block, and then the thread releases the lock.

2. Thread execution is abnormal, at this time JVM will let the thread release the lock automatically.

3. This is mainly the wait() method in the waiting wake-up mechanism, which releases the lock immediately when waiting to facilitate other threads to use the lock. And when awakened, awaken right here.

Although we can understand the lock object problem of synchronized code blocks and synchronized methods, we have not directly seen where the lock is added and where the lock is released, and at the same time, in order to better release the lock.
Lock object Lock:

(You can know whether the thread has successfully acquired the lock through Lock. This is something that synchronized cannot do)

1. Lock is not a built-in Java language, synchronized is a keyword of the Java language, so it is a built-in feature. Lock is a class through which synchronous access can be achieved.

2. Synchronized is implemented at the JVM level. Not only can the synchronized lock be monitored through some monitoring tools, but also when an exception occurs during code execution, the JVM will automatically release the lock, but using Lock will not work. The lock is implemented through code. To ensure that the lock will be released, you must put unLock() in finally{}.

3. When the resource competition is not very fierce, the performance of synchronized is better than that of ReetrantLock, but when the resource competition is very fierce, the performance of synchronized will drop dozens of times.
Simple example of Lock usage: (Sales of train tickets)

package code;

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

/**
 *
 * sellTicket.java
 * @author 董欣欣
 * @date 2017年4月9日 上午8:55:04
 */
public class sellTicket implements Runnable{

    private static int num=30;
    private Lock lock=new ReentrantLock();
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(num>0){
            try{
                lock.lock();
                if(num>0){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"正在出售"+num--);
                }
            }finally{
                lock.unlock();
            }
        }
    }
}

    
 

package code;
 
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
/**
 *
 * sellTicket.java
 * @author 董欣欣
 * @date 2017年4月9日 上午8:55:04
 */
public class sellTicket implements Runnable{
 
    private static int num=30;
    private Lock lock=new ReentrantLock();
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(num>0){
            try{
                lock.lock();
                if(num>0){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"正在出售"+num--);
                }
            }finally{
                lock.unlock();
            }
        }
    }
}

testing method:
 

public static void main(String args[]) {
        sellTicket str = new sellTicket();
        Thread tr1 = new Thread(str, "窗口1");
        Thread tr2 = new Thread(str, "窗口2");
        Thread tr3 = new Thread(str, "窗口3");
        tr1.start();
        tr2.start();
        tr3.start();
    }

    
public static void main(String args[]) {
        sellTicket str = new sellTicket();
        Thread tr1 = new Thread(str, "窗口1");
        Thread tr2 = new Thread(str, "窗口2");
        Thread tr3 = new Thread(str, "窗口3");
        tr1.start();
        tr2.start();
        tr3.start();
    }

 

Guess you like

Origin blog.csdn.net/yucaifu1989/article/details/107960979