欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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) {
        }
}
}
相关标签: 多线程