java中的并发性 - 如何测试它?

reg*_*reg 3 java

我目前正在使用Java并发.

我不知道怎么写负面情景测试.

我需要一种方法来制造死锁,我需要一种方法来看到,如果不使用同步,我可能会遇到像不一致这样的问题.

通常最好的方法是编写一些压力测试代码,如果省略同步,可能会显示不良结果?

任何代码示例都会非常适合.

谢谢大家!

Ada*_*ski 6

以下代码几乎肯定会创建一个死锁并演示经典的死锁场景,即两个不同的线程以不一致的顺序获取锁.

public class Main {
  private final Object lockA = new Object();
  private final Object lockB = new Object();

  public static void main(String[] args) {
    new Main();
  }

  public Main() {
    new Thread(new Runnable() {
      public void run() {
        a();
        sleep(3000L); // Add a delay here to increase chance of deadlock.
        b();
      }
    }, "Thread-A").start();

    new Thread(new Runnable() {
      public void run() {
        // Note: Second thread acquires locks in the reverse order of the first!
        b();
        sleep(3000L); // Add a delay here to increase chance of deadlock.
        a();
      }
    }, "Thread-A").start();
  }

  private void a() {
    log("Trying to acquire lock A.");

    synchronized(lockA) {
      log("Acquired lock A.");
    }
  }

  private void b() {
    log("Trying to acquire lock B.");

    synchronized(lockB) {
      log("Acquired lock B.");
    }
  }

  private void sleep(long millis) {
    try {
      Thread.sleep(millis);
    } catch(InterruptedException ex) {
    }
  }

  private void log(String msg) {
    System.err.println(String.format("Thread: %s, Message: %s",
      Thread.currentThread().getName(), msg));
  }
}
Run Code Online (Sandbox Code Playgroud)

以下代码演示了由于两个线程之间缺乏并发控制而可能会产生不一致结果的情况.

public class Main {
  // Non-volatile integer "result".
  private int i;

  public static void main(String[] args) {
    new Main();
  } 

  public Main() {
    Thread t1 = new Thread(new Runnable() {
      public void run() {
        countUp();
      }
    }, "Thread-1");

    Thread t2 = new Thread(new Runnable() {
      public void run() {
        countDown();
      }
    }, "Thread-2");

    t1.start();
    t2.start();

    // Wait for two threads to complete.
    t1.join();
    t2.join();

    // Print out result.  With correct concurrency control we expect the result to
    // be 0.  A non-zero result indicates incorrect use of concurrency.  Also note
    // that the result may vary between runs because of this.
    System.err.println("i: " + i);
  }

  private void countUp() {
    // Increment instance variable i 1000,000 times.  The variable is not marked
    // as volatile, nor is it accessed within a synchronized block and hence
    // there is no guarantee that the value of i will be reconciled back to main
    // memory following the increment.
    for (int j=0; j<1000000; ++j) {
      ++i;
    }
  }

  private void countDown() {
    // Decrement instance variable i 1000,000 times.  Same consistency problems
    // as mentioned above.
    for (int j=0; j<1000000; ++j) {
      --i;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)