62,623
社区成员
发帖
与我相关
我的任务
分享public class Test extends Thread {
@Override
public void run() {
while (true) {
getObject((int) (Math.random() * 100));
getObject(1000);
}
}
public void getObject(int id) {
String lock = String.valueOf(id).intern();
synchronized (lock) {
System.out.printf("%s: %d START%n", getName(), id);
try {
sleep(500);
} catch (InterruptedException e) {
}
System.out.printf("%s: %d END%n", getName(), id);
}
}
public static void main(String[] args) throws Exception {
new Test().start();
new Test().start();
new Test().start();
}
}
HashMap<Integer,Object> locks = new HashMap<Integer,Object>();
{
locks.put(1,new Object());
locks.put(2,new Object());
}
public void getObject(int id){
synchronized(locks.get(id)){
//
}
}
Object accountLock1 = new Object();
Object accountLock2 = new Object();
public void getObject(int id){
Ojbect lock = null;
if (id == 1)
lock = accountLock1;
else if (id == 2)
lock = accountLock2;
synchronized(lock) {
//........
}
}