gpt4 book ai didi

java - 使用 volatile 来避免竞争条件

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:44:00 25 4
gpt4 key购买 nike

<分区>

我正在学习 java.util.concurrent。我写了一些这样的代码:

import java.util.concurrent.ArrayBlockingQueue;

public class JUCArrayBlockingQueue {

private static ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(1);
private static volatile int i = 0;
private static volatile int j = 0;

public static void main(String[] args) {
new Pop("t1").start();
new Pop("t2").start();
new Push("p1").start();
new Push("p2").start();
}

static class Pop extends Thread {
public Pop(String name) {
super(name);
}

@Override
public void run() {

String str;
try {

while (++j < 500) {
str = abq.take();
System.out.println(j + ">>"
+ Thread.currentThread().getName() + " take: "
+ str);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

static class Push extends Thread {
public Push(String name) {
super(name);
}

@Override
public void run() {

while (i < 500) {
if (abq.offer(Thread.currentThread().getName() + " t" + i
+ " ~")) {
i++;
}
;
}
}
}
}

结果是这样的:

488>>t1 take: p2 t486  ~
489>>t2 take: p2 t487 ~
490>>t2 take: p1 t488 ~
491>>t1 take: p1 t489 ~
492>>t1 take: p2 t490 ~
493>>t1 take: p1 t490 ~
494>>t2 take: p1 t492 ~
495>>t2 take: p1 t493 ~
496>>t1 take: p1 t494 ~
497>>t2 take: p1 t495 ~
498>>t1 take: p1 t496 ~
499>>t2 take: p1 t497 ~
500>>t1 take: p2 t498 ~

我对这个输出感到困惑,因为左边的尺寸是预期的,而不是右边的尺寸。我没想到会在右侧显示重复值。我该如何解决?有人帮忙吗?

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