我想試一下synchronized關(guān)鍵字是不是有效?所以寫了一個很簡單的類,但是就是不能調(diào)到數(shù)字按序排列。不知道錯在哪里了。數(shù)字序列類:[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]可是結(jié)果是:[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]我想讓數(shù)字按序排列,可是數(shù)字沒有按序排列,請問哪里寫錯了,謝謝
添加回答
舉報
0/150
提交
取消