如何证明类不是线程安全的

时间:2020-11-03 21:00:10

标签: java multithreading

我对线程有点陌生。如何通过在单独的类中编写代码来证明 MyClass 类不是线程安全的?我一直在搜索,但是我找不到真正能帮助我的例子。

public class MyClass {
  private static int value = 0;
  
  public static void set(int setVal) {
    value = setVal;
  }

  public static int get() {
    return value;
  }  

  public static void decrement() {
    int temp = value;
    value = --temp;
  }
}

1 个答案:

答案 0 :(得分:2)

public static void main(String[] args) {
    int nt = 10;
    int c = 20000;

    MyClass.set(c);

    Thread[] threads = new Thread[nt];

    for (int t = 0; t < nt; t++) {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < c; i += nt) {
                MyClass.decrement();
            }
        });
        thread.start();
        threads[t] = thread;
    }

    try {
        for (Thread thread : threads) {
            thread.join();
        }
    } catch (Throwable tr) {
        tr.printStackTrace();
    }

    System.out.println(MyClass.get());
}

尝试一下。如果将同步添加到MyClass的减量方法中,它将打印出0(线程安全),但是如果不同步减量,它将打印出错误的数字。

这证明MyClass(其减量方法)不是线程证明,因为如果是,它将输出0。

此外,如果您不能使用lambda而不是将第一个for循环替换为以下内容:

for (int t = 0; t < nt; t++) {
    Thread thread = new Thread(() -> {
        for (int i = 0; i < c; i += nt) {
            MyClass.decrement();
        }
    });
    thread.start();
    threads[t] = thread;
}

希望我能帮上忙!