62,614
社区成员
发帖
与我相关
我的任务
分享
class ThreadTest extends Thread {
final private Integer ID;
private ThreadTest(Integer id) {
super();
ID = id;
}
public void run() {
synchronized (ID) {
// do sth here;
}
}
}
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class Test {
private static ConcurrentMap<Integer, Object> map = new ConcurrentHashMap<Integer, Object>();
public static void main(String[] args) throws InterruptedException {
// Random r = new Random();
// for (int i = 0; i < 10; i++) {
// new T(r.nextInt(10)).start();
// }
new ThreadTest(1).start();
new ThreadTest(1).start();
new ThreadTest(2).start();
new ThreadTest(2).start();
}
static class ThreadTest extends Thread {
private int id;
public ThreadTest(int id) {
this.id = id;
}
public void run() {
if (hasId()) {
System.out.println("sync......");
}
synchronized (map.get(id)) {
doSomeThing();
}
map.remove(id);
}
private boolean hasId() {
synchronized (map) {
if (!map.containsKey(id)) {
Object lock = new Object();
map.put(id, lock);
return false;
}
return true;
}
}
void doSomeThing() {
try {
System.out.println(id + " doing something .....");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}