2013-09-27 56 views
1

我正在尝试使用方法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 

回答

3

您已经​​一个实例方法。它将在实例本身上进行同步。但是,您的每个Thread s正在使用不同的实例,即。它们在不同的对象上各自为​​,因此不会彼此阻塞。

你需要分享您的Test实例

Test a = new Test("A"); 
Thread t1 = new Thread(a); 
Thread t2 = new Thread(a); 

或不同的共享对象使用​​。您可以通过传递锁对象作为构造函数参数或使用静态字段引用来完成此操作。

+0

怎么了downvote? –

1

方法​​的问题是它锁定在this上。在你的情况下,你有2个不同的实例 - 他们每个人都有不同的this参考。一个方法使用​​字是一样的这样做:

public void m1() { 
    synchronized(this) { 
     // Critical code section here 
    } 
} 

如果你想要做你描述你的代码看起来应该是这样的锁:

public class Test implements Runnable{ 

    private final static Object lock = new Object(); 

    public void run(){ 
     m1(); 
    } 

    public void m1(){ 
     synchronized(lock) { 
      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(); 

    } 

} 

在这种情况下,您共享在两个实例之间锁定(因为它是静态的),这样就锁定了同一个对象,并按照您希望的方式进行同步。