Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class DemonstrationOfReadWriteLock {
- public static void main(String[] args) throws InterruptedException {
- ReadWriteLock lock = new ReadWriteLock();
- Thread writer1 =
- new Thread(
- () -> {
- try {
- System.out.println("Writer 1 Attempting to acquire write lock");
- lock.acquireWriteLock();
- System.out.println("Writer 1 Acquired write lock");
- } catch (InterruptedException e) {
- }
- });
- Thread writer2 =
- new Thread(
- () -> {
- try {
- System.out.println("Writer 2 Attempting to acquire write lock");
- lock.acquireWriteLock();
- System.out.println("Writer 2 Acquired write lock");
- } catch (InterruptedException e) {
- }
- });
- Thread writer3 =
- new Thread(
- () -> {
- try {
- System.out.println("Writer 3 Attempting to release write lock");
- lock.releaseWriteLock();
- System.out.println("Writer 3 Released write lock");
- } catch (InterruptedException e) {
- }
- });
- Thread reader1 =
- new Thread(
- new Runnable() {
- @Override
- public void run() {
- try {
- System.out.println("Reader 1 Attempting to acquire read lock");
- lock.acquireReadLock();
- System.out.println("Reader 1 Acquired read lock");
- } catch (InterruptedException e) {
- }
- }
- });
- Thread reader2 =
- new Thread(
- () -> {
- try {
- System.out.println("Reader 2 Attempting to release read lock");
- lock.releaseReadLock();
- System.out.println("Reader 2 Released read lock");
- } catch (InterruptedException e) {
- }
- });
- reader1.start();
- Thread.sleep(100);
- writer1.start();
- Thread.sleep(100);
- reader2.start();
- reader1.join();
- reader2.join();
- Thread.sleep(100);
- writer2.start();
- Thread.sleep(100);
- writer3.start();
- Thread.sleep(100);
- writer1.join();
- writer2.join();
- writer3.join();
- }
- }
- class ReadWriteLock {
- private int readers = 0;
- private boolean writer = false;
- public synchronized void acquireReadLock() throws InterruptedException {
- while (writer) {
- wait();
- }
- readers++;
- }
- public synchronized void releaseReadLock() throws InterruptedException {
- readers--;
- notify();
- }
- public synchronized void acquireWriteLock() throws InterruptedException {
- while (writer || readers > 0) {
- wait();
- }
- writer = true;
- }
- public synchronized void releaseWriteLock() throws InterruptedException {
- writer = false;
- notifyAll();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement