簡體   English   中英

在Java中使用不同的對象進行一次同步/鎖定

[英]Using different objects for one synchronization/lock in Java

我有兩個不同的對象,但它們是相等的(obj1!= obj2,但是obj1.equlas(obj2))

如何使用同步/鎖定這樣的對象? 例如:

...
synchronized(obj) {
        doSomething(obj);
}
...

如果equals()對象之一已經在同一時間做某事,我想鎖定它。

沒有辦法只使用一個同步的(對象)並使兩個對象同步。

解決方案是:

synchronized (obj) {
      synchronized (obj2) { ......

但是,如果您在另一個線程上反轉順序,則會死鎖。

我建議的另一種解決方案是使obj靜態並用於同步。

您所擁有的實際上是等於對象,但是您對obj和obj2擁有的變量引用指向的是不同的對象。

我不能說我完全理解為什么可能需要這樣做,但是使用包裝器方法可能會有所幫助:

public class SyncOnEquals {
    public synchronized Object getSync(Object o1, Object o2)
    {
        if(o1.equals(o2))
            return this;
        else
            return o1;
    }
}

測試:

@org.junit.Test
public void testSyncOnEqual() {
System.out.println("syncOnEqual");
Integer o1 = new Integer(125);
Integer o2 = new Integer(125);

System.out.println("o1 == o2: "+(o1==o2));
System.out.println("o1.equals(o2): "+o1.equals(o2));
SyncOnEquals sync = new SyncOnEquals();

Thread t1 = new Thread(){
    public void run()
    {
        System.out.println("Waiting thread "+Thread.currentThread());
        synchronized(sync.getSync(o1, o2))
        {
            System.out.println("Working thread "+Thread.currentThread());
            try {
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("Finished thread "+Thread.currentThread());
    }
};

Thread t2 = new Thread(){
    public void run()
    {
        System.out.println("Waiting thread "+Thread.currentThread());
        synchronized(sync.getSync(o2, o1))
        {
            System.out.println("Working thread "+Thread.currentThread());
            try {
                Thread.currentThread().sleep(500);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("Finished thread "+Thread.currentThread());
    }
};

t1.start();
t2.start();

try{
    Thread.currentThread().sleep(2000);
} catch (InterruptedException ex) {
    ex.printStackTrace();

    }
}

輸出:

syncOnEqual
o1 == o2: false
o1.equals(o2): true
Waiting thread Thread[Thread-0,5,main]
Waiting thread Thread[Thread-1,5,main]
Working thread Thread[Thread-0,5,main]
Finished thread Thread[Thread-0,5,main]
Working thread Thread[Thread-1,5,main]
Finished thread Thread[Thread-1,5,main]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM