Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deal with Lock synchronization of lock object of Java thread

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to handle Lock synchronization of Java thread lock objects". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Lock is an interface under the java.util.concurrent.locks package. Lock implementation provides a wider range of locking operations than using synchronized methods and statements. It can deal with thread synchronization problems in a more elegant way. Let's simply implement the same effect as sychronized with an example in thread synchronization synchronized and volatile detailed explanation of Java threads. The code is as follows:

Public class LockTest {public static void main (String [] args) {final Outputter1 output = new Outputter1 (); new Thread () {public void run () {output.output ("zhangsan");}. Start (); new Thread () {public void run () {output.output ("lisi");};}. Start () }} class Outputter1 {private Lock lock = new ReentrantLock (); / / Lock object public void output (String name) {/ / TODO thread output method lock.lock (); / / get the lock try {for (int I = 0; I < name.length (); iTunes +) {System.out.print (name.charAt (I));}} finally {lock.unlock () / / release the lock}

This achieves the same synchronization effect as sychronized, it should be noted that the lock is automatically released after the code is executed with a sychronized-modified method or statement block, while using Lock requires us to release the lock manually, so in order to ensure that the lock is eventually released (an exception occurs), put the mutex area in the try and release the lock in the finally.

If this is Lock, then it can not be a more perfect way to deal with synchronization problems, the following is to introduce read-write locks (ReadWriteLock), we will have a demand, in order to ensure the consistency and integrity of data, we need to read and write mutually exclusive, write and write are mutually exclusive, but read and read do not need to be mutually exclusive, so read and read are more mutually exclusive Take a look at code prototypes that do not take into account mutexes:

Public class ReadWriteLockTest {public static void main (String [] args) {final Data data = new Data (); for (int I = 0; I < 3; iTunes +) {new Thread (new Runnable () {public void run () {for (int j = 0; j < 5; jacks +) {data.set (new Random (). NextInt (30)) }) .start ();} for (int I = 0; I < 3; iTunes +) {new Thread (new Runnable () {public void run () {for (int j = 0; j < 5; jacks +) {data.get ();}) .start () } class Data {private int data;// shared data public void set (int data) {System.out.println (Thread.currentThread (). GetName () + "prepare to write data"); try {Thread.sleep (20);} catch (InterruptedException e) {e.printStackTrace ();} this.data = data System.out.println (Thread.currentThread (). GetName () + "write" + this.data);} public void get () {System.out.println (Thread.currentThread (). GetName () + "ready to read data"); try {Thread.sleep (20);} catch (InterruptedException e) {e.printStackTrace () } System.out.println (Thread.currentThread () .getName () + read + this.data);}}

Partial output:

Thread-1 prepares to write data Thread-3 prepares to read data Thread-2 prepares to write data Thread-0 prepares to write data Thread-4 prepares to read data Thread-5 prepares to read data Thread-2 writes 12 Thread-4 reads 12 Thread-5 reads 5 Thread-1 writes 12

We want to implement write and write mutex, read and write mutex, read and read mutex, and add sychronized modifiers to the set and get methods:

Public synchronized void set (int data) {...} public synchronized void get () {...}

Partial output:

Thread-0 ready to write data Thread-0 write 9 Thread-5 ready to read data Thread-5 read 9 Thread-5 ready to read data Thread-5 read 9

We find that although write and write are mutually exclusive and read and write are mutually exclusive, they are also mutually exclusive and cannot be executed concurrently, which is inefficient. The implementation code with read-write lock is as follows:

Class Data {private int data;// shared data private ReadWriteLock rwl = new ReentrantReadWriteLock (); public void set (int data) {rwl.writeLock () .lock (); / / get the write lock try {System.out.println (Thread.currentThread (). GetName () + "prepare to write data"); try {Thread.sleep (20);} catch (InterruptedException e) {e.printStackTrace () } this.data = data; System.out.println (Thread.currentThread (). GetName () + "write" + this.data);} finally {rwl.writeLock () .unlock (); / / release write lock}} public void get () {rwl.readLock () .lock () / get the read lock try {System.out.println (Thread.currentThread (). GetName () + "ready to read data"); try {Thread.sleep (20);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println (Thread.currentThread (). GetName () + "read" + this.data);} finally {rwl.readLock (). Unlock () / / release the read lock}

Partial output:

Thread-4 prepares to read data Thread-3 prepares to read data Thread-5 prepares to read data Thread-5 reads 18 Thread-4 reads 18 Thread-3 reads 18 Thread-2 prepares to write data Thread-2 writes 6 Thread-2 prepares to write data Thread-2 writes 10 Thread-1 prepares to write data Thread-1 writes 22 Thread-5 prepares to read data "Java thread's lock object Lock synchronization question processing" content ends here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report