我正在尝试使用同步方法运行示例线程模块,但结果与预期的不一样。
因为我已经同步了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
您有synchronized
一个实例方法。它将在实例本身上同步。但是,您Thread
的每个都使用不同的实例,即。它们各自synchronized
位于不同的对象上,因此不会互相阻塞。
您需要分享您的Test
实例
Test a = new Test("A");
Thread t1 = new Thread(a);
Thread t2 = new Thread(a);
或synchronized
在其他共享对象上使用。您可以通过将锁定对象作为构造函数参数传递或使用静态字段引用来实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句