Following code found that output results is not the order, not from small to large, how to guarantee it is order from small to large?
java code
public class TestSync {
/**
* @param args
*/
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Thread1()).start();
}
}
public int getNum(int i) {
synchronized (this) {
i++;
}
return i;
}
static class Thread1 implements Runnable {
static Integer value = 0;
@Override
public void run() {
TestSync ts = new TestSync();
value = ts.getNum(value);
System.out.println("thread1:" + value);
}
}
}
What are you trying to accomplish? Your code is only synchronizing calls made to a particular
TestSyncinstance. Since each thread creates its own instance, it’s like you are not synchronizing anything at all. Your code is not doing anything to synchronize or coordinate accesses across the different threads.I’d suggest the following code may be more along the lines of what you are trying to accomplish:
Live example here: http://ideone.com/BGUYY
Note that
getNum()is essentially superfluous. The example above would work the same if you replacedvalue = getNum(value);with a simplevalue++;.