package concurrent.rwl;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class MyWriteAndReadTest {
private static Random random = new Random();
private static int threadCount = 50;
private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
static String data = "";
private static class Write implements Runnable{
@Override
public void run() {
Lock wl = lock.writeLock();
wl.lock();
try {
long time = random.nextInt(20) * 100L;
System.out.println(Thread.currentThread().getName() +" 开始写 : " + time);
Thread.sleep(time);
data = randomPool(10);
System.out.println(Thread.currentThread().getName() +" 结束写 : " + time);
System.out.println("写 = " + data);
System.out.println();
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
wl.unlock();
}
}
}
private static class Read implements Runnable{
@Override
public void run() {
Lock rl = lock.readLock();
rl.lock();
try {
long time = random.nextInt(20) * 100L;
System.out.println(Thread.currentThread().getName() +" 开始读 : " + time);
Thread.sleep(time);
System.out.println(Thread.currentThread().getName() +" 结束读 : " + time);
System.out.println("读 = " + data);
System.out.println();
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
rl.unlock();
}
}
}
private static String randomPool(int size){
StringBuilder sb = new StringBuilder();
for(int i=0;i<size;i++){
sb.append((char)(random.nextInt(25)+'a'));
}
return sb.toString();
}
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(8,16,1l, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>());
for(int i=0;i<20;i++){
if(random.nextInt()%2==0) {
threadPoolExecutor.execute(new MyWriteAndReadTest.Write());
}
else{
threadPoolExecutor.execute(new MyWriteAndReadTest.Read());
}
}
threadPoolExecutor.shutdown();
}
}
参考 参考 参考
|