同步块使用不同的对象

时间:2013-07-19 14:40:55

标签: java synchronization

我们使用什么对象来锁定同步块是否真的重要。

例如,我有2个代码片段,如下所示。 两者产生相同的输出。我只更改了用于锁定同步块的对象

代码1:

package test.thread.synchronization;
public class Run1 implements Runnable{
String ts1=null;
public Run1(String ts1){
    this.ts1=ts1;
}
    @Override
public void run() {
    // TODO Auto-generated method stub
    run1Print();
}
public  void run1Print(){
    synchronized(ts1){
    for(int i =0;i<10;i++){
        System.out.println("run1Print: "+Thread.currentThread().getName()+":"+i);
    try{
    Thread.sleep(1000);
    }catch(InterruptedException e){
        e.printStackTrace();
    }
    }
    }
}
}

====

package test.thread.synchronization;
public class Run2 implements Runnable{
String ts1=null;
public Run2(String ts1){
    this.ts1=ts1;
}
@Override
public void run() {
    // TODO Auto-generated method stub
    run2Print();
}
public void run2Print(){
    synchronized(ts1){
//  System.out.println("Decrement");

    for(int i =0;i<10;i++){
        System.out.println("run2Print: "+Thread.currentThread().getName()+":"+i);
    try{
    Thread.sleep(1000);
    }catch(InterruptedException e){
        e.printStackTrace();
    }
    }
    }
}
}

=====

 package test.thread.synchronization;
 public class Ts1 {
public static void main(String[] args) {

    // Ts1 ts1 = new Ts1();
    String ts1 = "";
    Run1 tr1 = new Run1(ts1);
    Run2 tr2 = new Run2(ts1);
    Thread t1 = new Thread(tr1);
    Thread t2 = new Thread(tr2);
    t1.start();
    t2.start();
}

}

代码2:

package test.thread.synchronization;
public class Run1 implements Runnable{
Ts1 ts1=null;
public Run1(Ts1 ts1){
    this.ts1=ts1;
}
@Override
public void run() {
    // TODO Auto-generated method stub
    run1Print();
}
public  void run1Print(){
    synchronized(ts1){
    for(int i =0;i<10;i++){
        System.out.println("run1Print: "+Thread.currentThread().getName()+":"+i);
    try{
    Thread.sleep(1000);
    }catch(InterruptedException e){
        e.printStackTrace();
    }
    }
    }
}
}

==

package test.thread.synchronization;
public class Run2 implements Runnable{
Ts1 ts1=null;
public Run2(Ts1 ts1){
    this.ts1=ts1;
}
@Override
public void run() {
    // TODO Auto-generated method stub
    run2Print();
}
public void run2Print(){
    synchronized(ts1){
//  System.out.println("Decrement");
    for(int i =0;i<10;i++){
        System.out.println("run2Print: "+Thread.currentThread().getName()+":"+i);
    try{
    Thread.sleep(1000);
    }catch(InterruptedException e){
        e.printStackTrace();
    }
    }
    }
}
}

==

package test.thread.synchronization;
public class Ts1 {
public static void main(String[] args) {

     Ts1 ts1 = new Ts1();
    //String ts1 = "";
    Run1 tr1 = new Run1(ts1);
    Run2 tr2 = new Run2(ts1);
    Thread t1 = new Thread(tr1);
    Thread t2 = new Thread(tr2);
    t1.start();
    t2.start();
}

}

1 个答案:

答案 0 :(得分:2)

对象类型无关紧要,但是您应该在唯一的final对象上进行同步,否则您可能会无意中在两个不同的对象上同步两个线程。