国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java JavaBase Detailed explanation of java concurrent programming

Detailed explanation of java concurrent programming

Dec 25, 2019 pm 05:12 PM
java

Detailed explanation of java concurrent programming

1. Defects of synchronized

synchronized is a keyword in java, that is to say It is a built-in feature of the Java language. So why does Lock appear?

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, and get it here There are only two situations when the lock's thread releases the lock:

1) The thread that acquired the lock finishes executing the code block, and then the thread releases its possession of the lock;

2) An exception occurs during thread execution , at this time the JVM will let the thread automatically release the lock.

Recommendation: Basic Java Tutorial

Then if the thread that acquires the lock is blocked due to waiting for IO or other reasons (such as calling the sleep method), but it does not After releasing the lock, other threads can only wait dryly. Just imagine how this affects the efficiency of program execution.

Therefore, there is a need for a mechanism that prevents the waiting thread from waiting indefinitely (such as only waiting for a certain time or being able to respond to interrupts), which can be done through Lock.

Another example: when multiple threads read and write files, read operations and write operations will conflict, write operations will conflict with write operations, but read operations and read operations will not occur. conflict phenomenon.

But using the synchronized keyword to achieve synchronization will lead to a problem:

If multiple threads are only performing read operations, so when one thread is performing a read operation, other threads Can only wait and cannot perform read operations.

Therefore, a mechanism is needed to prevent conflicts between threads when multiple threads are only performing read operations. This can be done through Lock.

In addition, through Lock you can know whether the thread has successfully acquired the lock. This is something synchronized cannot do.

To summarize, Lock provides more functions than synchronized. But pay attention to the following points:

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

2) There is a very big difference between Lock and synchronized. Using synchronized does not require the user to manually release the lock. When the synchronized method or synchronized code block is executed, After that, the system will automatically let the thread release the lock; with Lock, the user must manually release the lock. If the lock is not actively released, a deadlock may occur.

2. Commonly used classes under the java.util.concurrent.locks package

Let’s discuss java.util.concurrent. Commonly used classes and interfaces in the locks package.

1.Lock

The first thing to explain is Lock. By looking at the source code of Lock, we can see that Lock is an interface:

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

Let’s go through them one by one. Describe the use of each method in the Lock interface. lock(), tryLock(), tryLock(long time, TimeUnit unit) and lockInterruptibly() are used to obtain locks. The unLock() method is used to release the lock. The newCondition() method will not be described here for the time being, but will be discussed in a later article on thread collaboration.

Four methods are declared in Lock to obtain the lock, so what are the differences between these four methods?

First of all, the lock() method is the most commonly used method, which is used to obtain locks. If the lock has been acquired by another thread, wait.

As mentioned earlier, if you use Lock, you must actively release the lock, and when an exception occurs, the lock will not be automatically released. Therefore, generally speaking, the use of Lock must be carried out in the try{}catch{} block, and the operation of releasing the lock must be carried out in the finally block to ensure that the lock must be released and prevent the occurrence of deadlock. If Lock is usually used for synchronization, it is used in the following form:

Lock lock = ...;
lock.lock();
try{
    //處理任務(wù)
}catch(Exception ex){
     
}finally{
    lock.unlock();   //釋放鎖
}

tryLock() method has a return value, which means it is used to try to acquire the lock. If the acquisition is successful, it returns true , if the acquisition fails (that is, the lock has been acquired by another thread), false is returned, which means that this method will return immediately no matter what. You won't be waiting there when you can't get the lock.

The tryLock(long time, TimeUnit unit) method is similar to the tryLock() method, but the only difference is that this method will wait for a certain period of time when it cannot get the lock. If it still gets the lock within the time limit, If the lock is not reached, false is returned. Returns true if the lock was obtained initially or during the waiting period.

So, under normal circumstances, when acquiring a lock through tryLock, it is used like this:

Lock lock = ...;
if(lock.tryLock()) {
     try{
         //處理任務(wù)
     }catch(Exception ex){
         
     }finally{
         lock.unlock();   //釋放鎖
     } 
}else {
    //如果不能獲取鎖,則直接做其他事情
}

The lockInterruptibly() method is special. When acquiring a lock through this method, if the thread is waiting to acquire lock, then this thread can respond to the interrupt, that is, interrupt the waiting state of the thread.

That is to say, when two threads want to acquire a lock through lock.lockInterruptibly() at the same time, if thread A acquires the lock at this time, and thread B is only waiting, then call threadB on thread B The .interrupt() method can interrupt the waiting process of thread B.

由于lockInterruptibly()的聲明中拋出了異常,所以lock.lockInterruptibly()必須放在try塊中或者在調(diào)用lockInterruptibly()的方法外聲明拋出InterruptedException。

因此lockInterruptibly()一般的使用形式如下:

public void method() throws InterruptedException {
    lock.lockInterruptibly();
    try {  
     //.....
    }
    finally {
        lock.unlock();
    }  
}

注意,當(dāng)一個線程獲取了鎖之后,是不會被interrupt()方法中斷的。因為本身在前面的文章中講過單獨調(diào)用interrupt()方法不能中斷正在運行過程中的線程,只能中斷阻塞過程中的線程。

因此當(dāng)通過lockInterruptibly()方法獲取某個鎖時,如果不能獲取到,只有進(jìn)行等待的情況下,是可以響應(yīng)中斷的。

而用synchronized修飾的話,當(dāng)一個線程處于等待某個鎖的狀態(tài),是無法被中斷的,只有一直等待下去。

2.ReentrantLock

ReentrantLock,意思是“可重入鎖”,關(guān)于可重入鎖的概念在下一節(jié)講述。ReentrantLock是唯一實現(xiàn)了Lock接口的類,并且ReentrantLock提供了更多的方法。下面通過一些實例看具體看一下如何使用ReentrantLock。

例子1,lock()的正確使用方法

public class Test {
    private ArrayList<Integer> arrayList = new ArrayList<Integer>();
    public static void main(String[] args)  {
        final Test test = new Test();
         
        new Thread(){
            public void run() {
                test.insert(Thread.currentThread());
            };
        }.start();
         
        new Thread(){
            public void run() {
                test.insert(Thread.currentThread());
            };
        }.start();
    }  
     
    public void insert(Thread thread) {
        Lock lock = new ReentrantLock();    //注意這個地方
        lock.lock();
        try {
            System.out.println(thread.getName()+"得到了鎖");
            for(int i=0;i<5;i++) {
                arrayList.add(i);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }finally {
            System.out.println(thread.getName()+"釋放了鎖");
            lock.unlock();
        }
    }
}

輸出結(jié)果:

Thread-0得到了鎖
Thread-1得到了鎖
Thread-0釋放了鎖
Thread-1釋放了鎖

在insert方法中的lock變量是局部變量,每個線程執(zhí)行該方法時都會保存一個副本,那么理所當(dāng)然每個線程執(zhí)行到lock.lock()處獲取的是不同的鎖,所以就不會發(fā)生沖突。

知道了原因改起來就比較容易了,只需要將lock聲明為類的屬性即可。

public class Test {
    private ArrayList<Integer> arrayList = new ArrayList<Integer>();
    private Lock lock = new ReentrantLock();    //注意這個地方
    public static void main(String[] args)  {
        final Test test = new Test();
         
        new Thread(){
            public void run() {
                test.insert(Thread.currentThread());
            };
        }.start();
         
        new Thread(){
            public void run() {
                test.insert(Thread.currentThread());
            };
        }.start();
    }  
     
    public void insert(Thread thread) {
        lock.lock();
        try {
            System.out.println(thread.getName()+"得到了鎖");
            for(int i=0;i<5;i++) {
                arrayList.add(i);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }finally {
            System.out.println(thread.getName()+"釋放了鎖");
            lock.unlock();
        }
    }
}

這樣就是正確地使用Lock的方法了。

例子2,tryLock()的使用方法

public class Test {
    private ArrayList<Integer> arrayList = new ArrayList<Integer>();
    private Lock lock = new ReentrantLock();    //注意這個地方
    public static void main(String[] args)  {
        final Test test = new Test();
         
        new Thread(){
            public void run() {
                test.insert(Thread.currentThread());
            };
        }.start();
         
        new Thread(){
            public void run() {
                test.insert(Thread.currentThread());
            };
        }.start();
    }  
     
    public void insert(Thread thread) {
        if(lock.tryLock()) {
            try {
                System.out.println(thread.getName()+"得到了鎖");
                for(int i=0;i<5;i++) {
                    arrayList.add(i);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }finally {
                System.out.println(thread.getName()+"釋放了鎖");
                lock.unlock();
            }
        } else {
            System.out.println(thread.getName()+"獲取鎖失敗");
        }
    }
}

輸出結(jié)果:

Thread-0得到了鎖
Thread-1獲取鎖失敗
Thread-0釋放了鎖

例子3,lockInterruptibly()響應(yīng)中斷的使用方法:

public class Test {
    private Lock lock = new ReentrantLock();   
    public static void main(String[] args)  {
        Test test = new Test();
        MyThread thread1 = new MyThread(test);
        MyThread thread2 = new MyThread(test);
        thread1.start();
        thread2.start();
         
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.interrupt();
    }  
     
    public void insert(Thread thread) throws InterruptedException{
        lock.lockInterruptibly();   //注意,如果需要正確中斷等待鎖的線程,必須將獲取鎖放在外面,然后將InterruptedException拋出
        try {  
            System.out.println(thread.getName()+"得到了鎖");
            long startTime = System.currentTimeMillis();
            for(    ;     ;) {
                if(System.currentTimeMillis() - startTime >= Integer.MAX_VALUE)
                    break;
                //插入數(shù)據(jù)
            }
        }
        finally {
            System.out.println(Thread.currentThread().getName()+"執(zhí)行finally");
            lock.unlock();
            System.out.println(thread.getName()+"釋放了鎖");
        }  
    }
}
 
class MyThread extends Thread {
    private Test test = null;
    public MyThread(Test test) {
        this.test = test;
    }
    @Override
    public void run() {
         
        try {
            test.insert(Thread.currentThread());
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName()+"被中斷");
        }
    }
}

運行之后,發(fā)現(xiàn)thread2能夠被正確中斷。

3.ReadWriteLock

ReadWriteLock也是一個接口,在它里面只定義了兩個方法:

public interface ReadWriteLock {
    /**
     * Returns the lock used for reading.
     *
     * @return the lock used for reading.
     */
    Lock readLock();
 
    /**
     * Returns the lock used for writing.
     *
     * @return the lock used for writing.
     */
    Lock writeLock();
}

一個用來獲取讀鎖,一個用來獲取寫鎖。也就是說將文件的讀寫操作分開,分成2個鎖來分配給線程,從而使得多個線程可以同時進(jìn)行讀操作。下面的ReentrantReadWriteLock實現(xiàn)了ReadWriteLock接口。

4.ReentrantReadWriteLock

ReentrantReadWriteLock里面提供了很多豐富的方法,不過最主要的有兩個方法:readLock()和writeLock()用來獲取讀鎖和寫鎖。

下面通過幾個例子來看一下ReentrantReadWriteLock具體用法。

假如有多個線程要同時進(jìn)行讀操作的話,先看一下synchronized達(dá)到的效果:

public class Test {
    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
     
    public static void main(String[] args)  {
        final Test test = new Test();
         
        new Thread(){
            public void run() {
                test.get(Thread.currentThread());
            };
        }.start();
         
        new Thread(){
            public void run() {
                test.get(Thread.currentThread());
            };
        }.start();
         
    }  
     
    public synchronized void get(Thread thread) {
        long start = System.currentTimeMillis();
        while(System.currentTimeMillis() - start <= 1) {
            System.out.println(thread.getName()+"正在進(jìn)行讀操作");
        }
        System.out.println(thread.getName()+"讀操作完畢");
    }
}

這段程序的輸出結(jié)果會是,直到thread1執(zhí)行完讀操作之后,才會打印thread2執(zhí)行讀操作的信息。

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0讀操作完畢

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1讀操作完畢

而改成用讀寫鎖的話:

public class Test {
    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
     
    public static void main(String[] args)  {
        final Test test = new Test();
         
        new Thread(){
            public void run() {
                test.get(Thread.currentThread());
            };
        }.start();
         
        new Thread(){
            public void run() {
                test.get(Thread.currentThread());
            };
        }.start();
         
    }  
     
    public void get(Thread thread) {
        rwl.readLock().lock();
        try {
            long start = System.currentTimeMillis();
             
            while(System.currentTimeMillis() - start <= 1) {
                System.out.println(thread.getName()+"正在進(jìn)行讀操作");
            }
            System.out.println(thread.getName()+"讀操作完畢");
        } finally {
            rwl.readLock().unlock();
        }
    }
}

此時打印的結(jié)果為:

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0正在進(jìn)行讀操作

Thread-1正在進(jìn)行讀操作

Thread-0讀操作完畢

Thread-1讀操作完畢

說明thread1和thread2在同時進(jìn)行讀操作。

這樣就大大提升了讀操作的效率。

不過要注意的是,如果有一個線程已經(jīng)占用了讀鎖,則此時其他線程如果要申請寫鎖,則申請寫鎖的線程會一直等待釋放讀鎖。

如果有一個線程已經(jīng)占用了寫鎖,則此時其他線程如果申請寫鎖或者讀鎖,則申請的線程會一直等待釋放寫鎖。

關(guān)于ReentrantReadWriteLock類中的其他方法感興趣的朋友可以自行查閱API文檔。

5.Lock和synchronized的選擇

總結(jié)來說,Lock和synchronized有以下幾點不同:

1)Lock是一個接口,而synchronized是Java中的關(guān)鍵字,synchronized是內(nèi)置的語言實現(xiàn);

2)synchronized在發(fā)生異常時,會自動釋放線程占有的鎖,因此不會導(dǎo)致死鎖現(xiàn)象發(fā)生;而Lock在發(fā)生異常時,如果沒有主動通過unLock()去釋放鎖,則很可能造成死鎖現(xiàn)象,因此使用Lock時需要在finally塊中釋放鎖;

3)Lock可以讓等待鎖的線程響應(yīng)中斷,而synchronized卻不行,使用synchronized時,等待的線程會一直等待下去,不能夠響應(yīng)中斷;

4)通過Lock可以知道有沒有成功獲取鎖,而synchronized卻無法辦到。

5)Lock可以提高多個線程進(jìn)行讀操作的效率。

在性能上來說,如果競爭資源不激烈,兩者的性能是差不多的,而當(dāng)競爭資源非常激烈時(即有大量線程同時競爭),此時Lock的性能要遠(yuǎn)遠(yuǎn)優(yōu)于synchronized。所以說,在具體使用時要根據(jù)適當(dāng)情況選擇。

三.鎖的相關(guān)概念介紹

在前面介紹了Lock的基本使用,這一節(jié)來介紹一下與鎖相關(guān)的幾個概念。

1.可重入鎖

如果鎖具備可重入性,則稱作為可重入鎖。像synchronized和ReentrantLock都是可重入鎖,可重入性在我看來實際上表明了鎖的分配機制:基于線程的分配,而不是基于方法調(diào)用的分配。舉個簡單的例子,當(dāng)一個線程執(zhí)行到某個synchronized方法時,比如說method1,而在method1中會調(diào)用另外一個synchronized方法method2,此時線程不必重新去申請鎖,而是可以直接執(zhí)行方法method2。

看下面這段代碼就明白了:

class MyClass {
    public synchronized void method1() {
        method2();
    }
     
    public synchronized void method2() {
         
    }
}

上述代碼中的兩個方法method1和method2都用synchronized修飾了,假如某一時刻,線程A執(zhí)行到了method1,此時線程A獲取了這個對象的鎖,而由于method2也是synchronized方法,假如synchronized不具備可重入性,此時線程A需要重新申請鎖。但是這就會造成一個問題,因為線程A已經(jīng)持有了該對象的鎖,而又在申請獲取該對象的鎖,這樣就會線程A一直等待永遠(yuǎn)不會獲取到的鎖。

而由于synchronized和Lock都具備可重入性,所以不會發(fā)生上述現(xiàn)象。

2.可中斷鎖

可中斷鎖:顧名思義,就是可以相應(yīng)中斷的鎖。

在Java中,synchronized就不是可中斷鎖,而Lock是可中斷鎖。

如果某一線程A正在執(zhí)行鎖中的代碼,另一線程B正在等待獲取該鎖,可能由于等待時間過長,線程B不想等待了,想先處理其他事情,我們可以讓它中斷自己或者在別的線程中中斷它,這種就是可中斷鎖。

在前面演示lockInterruptibly()的用法時已經(jīng)體現(xiàn)了Lock的可中斷性。

3.公平鎖

公平鎖即盡量以請求鎖的順序來獲取鎖。比如同是有多個線程在等待一個鎖,當(dāng)這個鎖被釋放時,等待時間最久的線程(最先請求的線程)會獲得該所,這種就是公平鎖。

非公平鎖即無法保證鎖的獲取是按照請求鎖的順序進(jìn)行的。這樣就可能導(dǎo)致某個或者一些線程永遠(yuǎn)獲取不到鎖。

在Java中,synchronized就是非公平鎖,它無法保證等待的線程獲取鎖的順序。

而對于ReentrantLock和ReentrantReadWriteLock,它默認(rèn)情況下是非公平鎖,但是可以設(shè)置為公平鎖。

看一下這2個類的源代碼就清楚了:

Detailed explanation of java concurrent programming

在ReentrantLock中定義了2個靜態(tài)內(nèi)部類,一個是NotFairSync,一個是FairSync,分別用來實現(xiàn)非公平鎖和公平鎖。

我們可以在創(chuàng)建ReentrantLock對象時,通過以下方式來設(shè)置鎖的公平性:

ReentrantLock lock = new ReentrantLock(true);

如果參數(shù)為true表示為公平鎖,為fasle為非公平鎖。默認(rèn)情況下,如果使用無參構(gòu)造器,則是非公平鎖。

Detailed explanation of java concurrent programming

另外在ReentrantLock類中定義了很多方法,比如:

isFair()??????? //判斷鎖是否是公平鎖

isLocked()??? //判斷鎖是否被任何線程獲取了

isHeldByCurrentThread()?? //判斷鎖是否被當(dāng)前線程獲取了

hasQueuedThreads()?? //判斷是否有線程在等待該鎖

在ReentrantReadWriteLock中也有類似的方法,同樣也可以設(shè)置為公平鎖和非公平鎖。不過要記住,ReentrantReadWriteLock并未實現(xiàn)Lock接口,它實現(xiàn)的是ReadWriteLock接口。

4.讀寫鎖

讀寫鎖將對一個資源(比如文件)的訪問分成了2個鎖,一個讀鎖和一個寫鎖。

正因為有了讀寫鎖,才使得多個線程之間的讀操作不會發(fā)生沖突。

ReadWriteLock就是讀寫鎖,它是一個接口,ReentrantReadWriteLock實現(xiàn)了這個接口。

可以通過readLock()獲取讀鎖,通過writeLock()獲取寫鎖。

上面已經(jīng)演示過了讀寫鎖的使用方法,在此不再贅述。

原文地址:http://www.cnblogs.com/dolphin0520/p/3923167.html

The above is the detailed content of Detailed explanation of java concurrent programming. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

See all articles