ReadWriteLock读写锁 多线程
程序员文章站
2022-07-12 18:21:12
...
ReadWriteLock 读写锁:多读单写
public class LockTest {
ReadWriteLock lockTreeMap = new ReentrantReadWriteLock();
final TreeMap<Long, String> treeMap = new TreeMap<Long, String>();
public static void main(String[] args) {
LockTest lock = new LockTest();
lock.new TestThread().start();
lock.new TestThread().start();
lock.new TestThread().start();
lock.new TestThread().start();
lock.new TestThread().start();
lock.new TestThread().start();
}
class TestThread extends Thread{
public TestThread(){
}
public void run(){
test();
}
}
void test(){
int loop = 16;
for (int i = 0; i < loop; i++) {
String msg = null;
try {
lockTreeMap.readLock().lockInterruptibly();
try {
if (!treeMap.isEmpty()) {
msg = treeMap.firstEntry().getValue();
} else {
break;
}
} finally {
lockTreeMap.readLock().unlock();
}
} catch (InterruptedException e) {
}
}
System.out.println("***");
try {
lockTreeMap.writeLock().lockInterruptibly();
try {
if (!treeMap.isEmpty()) {
System.out.println("...");
}
} finally {
lockTreeMap.writeLock().unlock();
}
} catch (InterruptedException e) {
}
}
}
public class LockTest {
ReadWriteLock lockTreeMap = new ReentrantReadWriteLock();
final TreeMap<Long, String> treeMap = new TreeMap<Long, String>();
public static void main(String[] args) {
LockTest lock = new LockTest();
lock.new TestThread().start();
lock.new TestThread().start();
lock.new TestThread().start();
lock.new TestThread().start();
lock.new TestThread().start();
lock.new TestThread().start();
}
class TestThread extends Thread{
public TestThread(){
}
public void run(){
test();
}
}
void test(){
int loop = 16;
for (int i = 0; i < loop; i++) {
String msg = null;
try {
lockTreeMap.readLock().lockInterruptibly();
try {
if (!treeMap.isEmpty()) {
msg = treeMap.firstEntry().getValue();
} else {
break;
}
} finally {
lockTreeMap.readLock().unlock();
}
} catch (InterruptedException e) {
}
}
System.out.println("***");
try {
lockTreeMap.writeLock().lockInterruptibly();
try {
if (!treeMap.isEmpty()) {
System.out.println("...");
}
} finally {
lockTreeMap.writeLock().unlock();
}
} catch (InterruptedException e) {
}
}
}
上一篇: jdk中的多线程 多线程
下一篇: oracle恢复误删数据