public Object handleRead(Lock lock) throws InterruptedException {
try {
//模拟读操作
lock.lock();
System.out.println("thread:" + Thread.currentThread().getId() + " value:" + value);
Thread.sleep(1000);
return value;
} finally {
lock.unlock();
}
}
public Object handleWrite(Lock lock, int index) throws InterruptedException {
try {
//模拟写操作
lock.lock();
value = index;
Thread.sleep(1000);
System.out.println("thread:" + Thread.currentThread().getId() + " value:" + value);
return value;
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
final ReadAndWriteLock demo = new ReadAndWriteLock();
demo.setValue(0);
Runnable readRunnable = new Runnable() {
@Override
public void run() {
try {
//读锁
demo.handleRead(readLock);
//可重入锁
//demo.handleRead(lock);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Runnable writeRunnable = new Runnable() {
@Override
public void run() {
try {
//写锁
demo.handleWrite(readLock, (int) (Math.random() * 1000));
//可重入锁
//demo.handleWrite(lock, (int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
ExecutorService exec = new ThreadPoolExecutor(0, 200,
0, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
;
long startTime = System.currentTimeMillis();
for (int i = 0; i < 18; i++) {
exec.execute(readRunnable);
}
for (int i = 0; i < 18; i++) {
exec.execute(writeRunnable);
}
exec.shutdown();
exec.awaitTermination(60, TimeUnit.MINUTES);
long endTime = System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: " + (endTime - startTime) + "ms");
}
}
在这里读线程完全并行,而写会阻塞读。程序执行时间如下