我尝试使用 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
最佳答案
您已经同步
了一个实例方法。它将在实例本身上同步。但是,您的每个 Thread
都使用不同的实例,即。它们每个都在不同的对象上同步
,因此不会相互阻塞。
您需要共享您的测试
实例
Test a = new Test("A");
Thread t1 = new Thread(a);
Thread t2 = new Thread(a);
或在不同的共享对象上使用synchronized
。您可以通过将锁定对象作为构造函数参数传递或使用静态字段引用来执行此操作。
关于方法上的 Java 线程同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19040810/