如果另一个线程正在调用另一个方法,则阻止对方法的访问

时间:2014-04-02 09:00:25

标签: java multithreading thread-synchronization

假设我有两个线程,T1和T2。我想确保如果T1正在调用方法A1(),那么T2不能调用方法B1()。同样,如果T1正在调用方法A2(),那么T2应该无法调用方法B2()

我怎么能实现这个目标?

class A { 
    public void A1() {
    }

    public void A2() {
    }
}

class B {
    public void B1() {
    }

    public void B2() {
    }
}

1 个答案:

答案 0 :(得分:0)

你可以这样试试:

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) {}
    }
}

输出:

A1
A2
B1
B2