我正在嘗試使用方法Synchronization運行示例線程模塊,但結果不符合預期。方法上的Java線程同步
由於我已經同步了m1(),我期望線程1完全打印值0 ... 10,然後線程2開始運行。
但是,在這種情況下,數字印刷交替...
package threadexample;
public class Test implements Runnable{
public void run(){
m1();
}
public synchronized void m1(){
for (int i = 0; i < 10; i ++){
System.out.println(Thread.currentThread().getName() + " Value of i = " + i);
}
}
Test(String threadname){
super();
}
public static void main(String[] args){
Test a = new Test("A");
Test b = new Test("B");
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
t1.start();
t2.start();
}
}
Output:
Thread-0 Value of i = 0
Thread-1 Value of i = 0
Thread-0 Value of i = 1
Thread-1 Value of i = 1
Thread-0 Value of i = 2
Thread-1 Value of i = 2
Thread-0 Value of i = 3
Thread-1 Value of i = 3
Thread-0 Value of i = 4
Thread-1 Value of i = 4
Thread-0 Value of i = 5
Thread-1 Value of i = 5
Thread-0 Value of i = 6
Thread-1 Value of i = 6
Thread-0 Value of i = 7
Thread-1 Value of i = 7
Thread-0 Value of i = 8
Thread-1 Value of i = 8
Thread-0 Value of i = 9
Thread-1 Value of i = 9
怎麼了downvote? –