我想试一下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 startedMain endedTestThread[bt]:2TestThread[bt]:3TestThread[at]:1TestThread[at]:5TestThread[at]:6TestThread[at]:7TestThread[at]:8TestThread[bt]:4TestThread[bt]:9TestThread[bt]:10[/code]我想让数字按序排列,可是数字没有按序排列,请问哪里写错了,谢谢
添加回答
举报
0/150
提交
取消