下面代码发现输出结果不是顺序的,不是从小到大的顺序,如何保证是从小到大的顺序?
java代码
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);
}
}
}
最佳答案
你想完成什么?您的代码仅同步对特定 TestSync
实例的调用。由于每个线程都创建自己的实例,所以就像您根本没有同步任何东西一样。您的代码没有做任何事情来同步或协调不同线程之间的访问。
我建议以下代码可能更符合您要完成的目标:
public static void main (String[] args) throws java.lang.Exception {
for (int i = 0; i < 10; i++) {
new Thread1().start();
}
}
//no need for this to be an instance method, or internally synchronized
public static int getNum(int i) {
return i + 1;
}
static class Thread1 extends Thread {
static Integer value = 0;
@Override
public void run() {
while (value < 100) {
synchronized(Thread1.class) { //this ensures that all the threads use the same lock
value = getNum(value);
System.out.println("Thread-" + this.getId() + ": " + value);
}
//for the sake of illustration, we sleep to ensure some other thread goes next
try {Thread.sleep(100);} catch (Exception ignored) {}
}
}
}
此处为实例:http://ideone.com/BGUYY
请注意,getNum()
本质上是多余的。如果将 value = getNum(value);
替换为简单的 value++;
,上面的示例将同样有效。
关于Java:线程顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12152493/