开发者

How to lock individual methods in a common utility class?

I have written the following code:

public class ClassLevelSynch开发者_StackOverflow中文版ronization {
    public static void main(String[] args) {
        new Thread(new AddThread()).start();
        new Thread(new MultiplyThread()).start();
    }
}

class UtilityCalculator{
    private static final Object ADD_LOCK = new Object();
    private static final Object MULTIPLY_LOCK = new Object();

    public static int add(int op1, int op2){
        synchronized (ADD_LOCK) {
            return op1+op2;
        }       
    }

    public static int multiply(int op1, int op2){
        synchronized (MULTIPLY_LOCK) {
            return op1*op2;
        }       
    }
}

class AddThread implements Runnable{
    public void run() {     
            for (int i = 0; i < 10; i++) {
                System.out.println("Addition of: "+i+" + "+(i+1)+" = "+UtilityCalculator.add(i, i+1));
            }   
    }
}

class MultiplyThread implements Runnable{
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Multiplication of: "+i+" * "+(i+1)+" = "+UtilityCalculator.multiply(i, i+1));
        }
    }
}

How do I ensure that the objects of AddThread and MultiplyThread can acquire locks for add(int op1, int op2) and multiply(int op1, int op2) methods respectively at the same time without blocking out each other?

In other words, I want to ensure that the two methods of UtilityCalculator class can be used simultaneously by two threads at any given time. How do I achieve this? Am I missing anything in the code?


You've already done it - you're synchronizing on different objects, so it should be fine. Is there some reason you suspect this isn't working?

To make it more obvious that it is working, put a sleep for a second inside each of the synchronization blocks. Your program will still execute all 20 operations in about 10 seconds, showing that the threads aren't blocking each other.


Those two methods already use two different objects to synchronize on, so you already can call and execute add and multiply at the same time from different threads.

Also, I assume you know this, but I have to add it, just to be sure: those method don't need any synchronization as all, as they are inherently thread-safe. If the actual code is just for demonstration, then feel free to ignore this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜