我创建了 1000 个线程来递增,1000 个线程来递减,1000 个线程来读取值。
每个增量线程,值增加25000倍。
每个递减线程,值减少25000倍。
每个读取线程读取该值 50000 次。
所以总的来说,读操作是占主导地位的。
读取值时放置 ReadLock
WriteLock 用于递增和递减值的方法。
观察结果:ReentrantReadWriteLock 大约需要 13000 ms Lock 大约需要 3000 ms。预期:ReentrantReadWriteLock 提供比 ReentrantLock 更快的性能。
顺便说一句:我个人认为使用 getCounter 方法时不需要锁定/同步(只需读取值)
import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Main {
public static void main(String[] args) throws InterruptedException {
ArrayList<Thread> reads = new ArrayList<>();
ArrayList<Thread> increments = new ArrayList<>();
ArrayList<Thread> decrements = new ArrayList<>();
Resources resources = new Resources();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) …Run Code Online (Sandbox Code Playgroud)