月度归档:2017年11月

多线程测试


public class SyncTest{
  private Long val = 1L;
//  private Long val = new Long(1L);
  private Object lock = new Object();

  public void printVal(int v){
    synchronized (lock){
      for (int i = 0; i < 50; i++) {
        System.out.print(v);
      }
    }
  }

  public void printVal2(int v){
    synchronized (SyncTest.class){
      for (int i = 0; i < 50; i++) {
        System.out.print(v);
      }
    }
  }

  public void printVal3(int v){
    synchronized (SyncTest.class) {
      for (int i = 0; i < 50; i++) {
        System.out.print(v);
      }
    }
  }

  public synchronized void printVal4(int v){
    for (int i = 0; i < 50; i++) {
      System.out.print(v);
    }
  }

  public synchronized void printVal5(int v){
    for (int i = 0; i < 50; i++) {
      System.out.print(v);
    }
  }

  public void printVal6(int v){
    val = (long)v; //同为一个st对象,但在同步时琐定到不对象,故也达不到同步的目的。
    synchronized (val) {
      for (int i = 0; i < 50; i++) {
        val++;
        System.out.print(v);
      }
    }
  }

  public void printVal7(int v){
    val = (long)v;
    synchronized (val) {
      for (int i = 0; i < 50; i++) {
        val++;
        System.out.print(v);
      }
    }
  }

  public void printVal8(int v){
    synchronized (this) {
      for (int i = 0; i < 50; i++) {
        val++;
        System.out.print(v);
      }
    }
  }

  public void printVal9(int v){
    synchronized (this) {
      for (int i = 0; i < 50; i++) {
        val++;
        System.out.print(v);
      }
    }
  }

  public static void main(String args[]) {
    final SyncTest st = new SyncTest();
    final SyncTest st2 = new SyncTest();
    Thread f1 = new Thread(new Runnable() {
      public void run() {
        st.printVal6(1);
      }
    });
    f1.start();
    Thread f2 = new Thread(new Runnable() {
      public void run() {
        st.printVal7(2);
      }
    });
    f2.start();
  }
}

1.修饰函数时,相同对象互斥,不同对象等同于没有synchronized
2.Long val=1L时,多个实例间仍然是同步的。故原子类型不合适作同步变量使用。
图示: