JUC in the package of multi-threaded read-write lock

When a plurality of threads simultaneously on a class attribute read and write operations tend to involve communication problems between multiple threads.

If multiple threads at the same time (write) or multiple threads at the same time (reading and writing), often want between threads are "mutually exclusive", that is, when one thread to access the class when a familiar (either read or write) We need to be locked to the reading and writing method, so that other threads in the meantime fighting for the cause data read and write multi-threaded access method is wrong.

The above situation inevitably bring about decrease in efficiency, we now consider the following scenario, if multiple threads simultaneously read, this situation is allowed to visit them at the same time, efficiency will increase.

After jdk1.5 provides a Java.util.concurrent package, which provides this interface ReadWriteLock provided ReentrantReadWriteLock implementation class, and two internal readlock writeLock methods, for implementing read-write lock individually distinguished, avoiding the Lock locking method class occupies a separate method for reading.

 1 package xianchengtest;
 2 
 3 import java.util.concurrent.locks.ReadWriteLock;
 4 import java.util.concurrent.locks.ReentrantReadWriteLock;
 5 
 6 public class TestReadWriteLock {
 7 
 8     public static void main(String[] args) {
 9         ReadWriteLockDemo rw = new ReadWriteLockDemo();
10         //一个写线程
11         new Thread(new Runnable() {
12             
13             @Override
14             public void run() {
15                 rw.set((int)(Math.random() * 101));
16             }
17         },"Write").start();
18         //多个读线程
19         for (int i = 0; i < 100; i++) {
20             
21             new Thread(new Runnable() {
22                 @Override
23                 public void run() {
24                     rw.get();
25                 }
26             },"Read").start();
27         }
28     }
29 }
30 
31 class ReadWriteLockDemo {
32     private int number= 0;
33     private ReadWriteLock lock = new ReentrantReadWriteLock();
34     
35     //read
36     public void get() {
37         lock.readLock().lock();
38         try {
39             
40             System.out.println(Thread.currentThread().getName()+ " : " + number);
41         } finally {
42             lock.readLock().unlock();
43         }
44     }
45     
46     //write
47     public void set(int number) {
48         lock.writeLock().lock();
49         try {
50             System.out.println(Thread.currentThread().getName());
51             this.number = number;
52         } finally {
53             lock.writeLock().unlock();
54         }
55     }
56 }

 

Guess you like

Origin www.cnblogs.com/blog-of-zxf/p/11126844.html