多线程问题中的java错误共享

pgccezyw  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(351)
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));
    }
}

输出: 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 然后我添加了注解 @ContendedpersonValuesB :

class Person extends Thread {
    //...

    public volatile static int personValuesA = 3;
    @Contended
    public volatile static int personValuesB = 1;
}

和输出: Duration 12 这两个程序同时运行。为什么?
我的问题:
为什么添加@confered注解后运行时间相同

3df52oht

3df52oht1#

@Contended 不适用于静态字段,仅适用于示例字段。

相关问题