forked from rinaldodev/java-multithread
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReentrantReadWriteLock_1.java
More file actions
55 lines (47 loc) · 1.43 KB
/
ReentrantReadWriteLock_1.java
File metadata and controls
55 lines (47 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* JAVA MULTITHREAD - ReentrantReadWriteLock
* @author youtube.com/RinaldoDev
*/
public class ReentrantReadWriteLock_1 {
private static int i = -1;
private static ReadWriteLock lock = new ReentrantReadWriteLock();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
Runnable r1 = () -> {
Lock writeLock = lock.writeLock();
writeLock.lock();
String name = Thread.currentThread().getName();
System.out.println(name + " - Escrevendo: " + i);
i++;
System.out.println(name + " - Escrito: " + i);
writeLock.unlock();
};
Runnable r2 = () -> {
Lock readLock = lock.readLock();
readLock.lock();
System.out.println("Lendo: " + i);
System.out.println("Lido: " + i);
readLock.unlock();
};
for (int i = 0; i < 6; i++) {
executor.execute(r1);
executor.execute(r2);
}
executor.shutdown();
}
}
//
//picpay.me/RinaldoDev
//apoia.se/rinaldodev
//
//YouTube: RinaldoDev
//Twitter: @rinaldodev
//Blog: rinaldo.dev
//LinkedIn: rinaldodev
//