我有一个名为MyRunnable的类:
public class MyRunnable extends Main implements Runnable {
String name; // name of thread
Thread t;
MyRunnable (String threadname) {
name = threadname;
t = new Thread(this, name);
t.start();
}
public void run() {
try {
for (int i=0;i<100000;i++) {
extend(1);
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Thread " + name + " exiting.");
}
}还有一个叫Main的班级:
public class Main {
private static List<Integer> numbers=new ArrayList<>();
public synchronized void extend (int i) throws InterruptedException {
numbers.add(i);
}
public synchronized static int getSize() {
return numbers.size();
}
public static void main(String[] args) {
MyRunnable t0=new MyRunnable("0");
MyRunnable t1=new MyRunnable("1");
MyRunnable t2=new MyRunnable("2");
try {
t0.t.join();
t1.t.join();
t2.t.join();
} catch (InterruptedException e) {
}
System.out.println(getSize());
}
}现在,我希望得到300000作为输出,但我得到一个随机数(大约。250000到290000之间),尽管我确实使用了同步方法。我确实读过甲骨文的文档http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html,但我似乎不明白为什么它不像预期的那样工作。有人能解释一下为什么吗?
提前感谢
发布于 2015-11-03 21:43:28
方法与调用它们的对象同步。您需要在每个对象之间创建一个共享的对象,并让它们在该对象上同步。
private static List<Integer> numbers=new ArrayList<>();
public synchronized void extend (int i) throws InterruptedException {
synchronize(numbers) {
numbers.add(i);
}
}发布于 2015-11-03 21:42:52
synchronized在这里锁定了调用extend方法的对象(因为它是一个实例方法)。因此,您正在对三个不同的对象进行同步。
如果您在共享static列表上进行同步(例如),您将得到预期的结果。
https://stackoverflow.com/questions/33509564
复制相似问题