我正在尝试使用方法 Synchronization 运行示例线程模块,但结果与预期不符。
由于我已经同步了 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