gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:58:01 26 4
gpt4 key购买 nike

我目前正在研究 Java 并发。

我不知道如何编写负面场景测试。

我需要一种制造死锁的方法,我需要一种不使用同步就能看到死锁的方法我最终可能会遇到不一致等问题。

编写一些压力测试代码的最佳方式通常是什么如果省略同步,这可能会给我带来不好的结果?

任何代码示例都非常适用。

提前谢谢大家!

最佳答案

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

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));
}
}

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

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;
}
}
}

关于java - Java 中的并发性——如何测试它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2342315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com