我有以下代碼。Java線程對象操作反映如何?
public class Test implements Runnable
{
static int id = 0;
int value = 0;
public static int getId() {
return ++id;
}
public static void main(String[] args)
{
Test t = new Test();
t.value = 10;
new Thread(t, "child " + getId()).start();
new Thread(t, "child " + getId()).start();
t.value = 20;
new Thread(t, "child " + getId()).start();
new Thread(t, "child " + getId()).start();
}
@Override
public void run() {
System.out.println("Thread " + Thread.currentThread().getName() + " started");
System.out.println(Thread.currentThread().getName() + " Data - " + this.value);
}
}
輸出上運行示例:
Thread child 1 started
Thread child 2 started
child 2 Data - 20
child 1 Data - 20
Thread child 3 started
child 3 Data - 20
Thread child 4 started
child 4 Data - 20
我可以看到線程對象的(測試)最新公佈的數據反映在所有的線程。但是如何?
我期待該線程開始,並應具有數據值「10」行t.value=20
之前執行。我錯了嗎?