62,635
社区成员




public class ThreadWriter {
static CyclicBarrier cyclicBarrier = new CyclicBarrier(10);
private static ReadWriteLock lock = new ReentrantReadWriteLock();
private static int number = 0;
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Thread() {
@Override
public void run() {
try {
System.err.println("线程" + Thread.currentThread().getName() + "到达!!!");
cyclicBarrier.await();
if (lock.writeLock().tryLock()) {
try {
Thread.sleep(10);
number++;
System.out.println(Thread.currentThread().getName() + "-------正在写-------");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
} else {
lock.readLock().lock();
System.out.println(Thread.currentThread().getName() + "-------正在读-------");
lock.readLock().unlock();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}