java - Java多线程错误共享问题
问题描述
class PersonValue {
volatile public int valueA;
@Contended
volatile public int valueB;
}
class Person extends Thread {
public final static long ITERATIONS = 500L * 1000L * 1000L ;
public static volatile PersonValue personValue = new PersonValue();
int index = 0;
public Person(int index) {
this.index = index;
}
@Override
public void run() {
long i = ITERATIONS;
while (--i > 0) {
if (index == 0) {
personValue.valueA = 3;
} else {
personValue.valueB = 3;
}
}
}
}
public class TestContend {
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Person person = new Person(0);
Person person1 = new Person(1);
person.start();
person1.start();
person.join();
person1.join();
long end = System.currentTimeMillis();
System.out.println("Duration " + TimeUnit.MILLISECONDS.toSeconds(end - start));
}
}
输出:</p>
Duration 3
当我在中注释@Contended
代码时PersonValue
,输出:
Duration 11
上面的输出符合我的预期,但是我修改了代码如下:
class Person extends Thread {
public final static long ITERATIONS = 500L * 1000L * 1000L ;
public volatile static int personValuesA = 3;
public volatile static int personValuesB = 1;
int index = 0;
public Person(int index) {
this.index = index;
}
@Override
public void run() {
long i = ITERATIONS;
while (--i > 0) {
if (index == 0) {
personValuesA = 3;
} else {
personValuesB = 3;
}
}
}
}
public class TestContend {
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Person person = new Person(0);
Person person1 = new Person(1);
person.start();
person1.start();
person.join();
person1.join();
long end = System.currentTimeMillis();
System.out.println("Duration" + TimeUnit.MILLISECONDS.toSeconds(end - start));
}
}
输出:
Duration 12
@Contended
然后我在中添加了注释personValuesB
:
class Person extends Thread {
//...
public volatile static int personValuesA = 3;
@Contended
public volatile static int personValuesB = 1;
}
并输出:
Duration 12
两个程序同时运行。为什么?
我的问题:
- 为什么添加@Contended注解后运行时间一样?</li>
解决方案
@Contended
不适用于静态字段,仅适用于实例字段。
推荐阅读
- powerbi - 如何在 Power BI 中合并包含相同 ID 的行并删除重复行的空值
- three.js - 希望通过使用另一个对象的轴心点来旋转一个对象
- google-chrome - chrome浏览器(v87)如何禁用cors检查
- ubuntu-16.04 - 更新 Ubuntu 更新 python 版本?
- image - 如何使图像颤动中的形状低于形状
- php - 使用php进行分页?
- python - 是否可以在 Openlayers 上旋转图像层?
- bash - 如何将多行输出解析为单独的变量
- javascript - OpenWeatherMap API 返回“未定义”
- c++ - 如何混淆或删除二进制文件中的导出名称