我想试一下synchronized关键字是不是有效?所以写了一个很简单的类,但是就是不能调到数字按序排列。不知道错在哪里了。
数字序列类:
[code="java"]
package com.testthread;
public class UnsafeSequence {
private int value = 0;
public synchronized int getValue(){
value = value+1;
return value;
}
}
[/code]
线程类
[code="java"]
package com.testthread;
public class TestThread extends Thread {
private UnsafeSequence us;
public TestThread(UnsafeSequence us, String threadname) {
super(threadname);
this.us = us;
}
@Override
public void run() {
String classname = this.getClass().getSimpleName();
String threadname = currentThread().getName();
for (int i = 0; i < 5; i++) {
System.out.println(classname + "[" + threadname + "]:"
+ us.getValue());
}
}
}
[/code]
Main类
[code="java"]
package com.testthread;
public class MainClass {
public static void main(String[] args) throws InterruptedException {
System.out.println("Main started");
UnsafeSequence us = new UnsafeSequence();
TestThread at = new TestThread(us,"at");
TestThread bt = new TestThread(us,"bt");
at.start();
bt.start();
System.out.println("Main ended");
}
}
[/code]
可是结果是:
[code="java"]
Main started
Main ended
TestThread[bt]:2
TestThread[bt]:3
TestThread[at]:1
TestThread[at]:5
TestThread[at]:6
TestThread[at]:7
TestThread[at]:8
TestThread[bt]:4
TestThread[bt]:9
TestThread[bt]:10
[/code]
我想让数字按序排列,可是数字没有按序排列,请问哪里写错了,谢谢