0

Suppose I have two threads, T1 and T2. I would like to ensure that if T1 is calling method A1(), then T2 cannot call method B1(). Similarly, if T1 is calling method A2(), then T2 should not be able to call method B2().

How might I achieve this?

class A { 
    public void A1() {
    }

    public void A2() {
    }
}

class B {
    public void B1() {
    }

    public void B2() {
    }
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
ZohebSiddiqui
  • 209
  • 3
  • 4
  • 14

1 Answers1

0

You may try it this way:

public static void main(String[] args) {
    final ReentrantReadWriteLock ONE = new ReentrantReadWriteLock();
    final ReentrantReadWriteLock TWO = new ReentrantReadWriteLock();

    Runnable t1 = new Runnable() {
        @Override public void run() {
            A a = new A();
            ONE.writeLock().lock();
            try { a.A1(); } finally { ONE.writeLock().unlock(); }
            TWO.writeLock().lock();
            try { a.A2(); } finally { TWO.writeLock().unlock(); }
        }
    };

    Runnable t2 = new Runnable() {
        @Override public void run() {
            B b = new B();
            ONE.writeLock().lock();
            try { b.B1(); } finally { ONE.writeLock().unlock(); }
            TWO.writeLock().lock();
            try { b.B2(); } finally { TWO.writeLock().unlock(); }
        }
    };
    new Thread(t1).start();
    new Thread(t2).start();
}

class A {
    public void A1() {
        System.out.println("A1");
        try { Thread.sleep(1000); } catch (InterruptedException e) {}
    }
    public void A2() {
        System.out.println("A2");
        try { Thread.sleep(1000); } catch (InterruptedException e) {}
    }
}

class B {
    public void B1() {
        System.out.println("B1");
        try { Thread.sleep(1000); } catch (InterruptedException e) {}
    }
    public void B2() {
        System.out.println("B2");
        try { Thread.sleep(1000); } catch (InterruptedException e) {}
    }
}

OUTPUT:

A1
A2
B1
B2
Harmlezz
  • 7,972
  • 27
  • 35
  • Worth noting that this prevents all code from accessing `B2()` when `A2()` is in use. This may be fine, but the OP's question is not clear on that subject - there is a suggestion that perhaps only specific threads should be affected by this. – Duncan Jones Apr 02 '14 at 09:15
  • Yes, you are right. If that is the case, both threads have to share a lock instead. – Harmlezz Apr 02 '14 at 09:21