【问题标题】:Conversion of AtomicInteger to int将 AtomicInteger 转换为 int
【发布时间】:2013-11-27 17:59:40
【问题描述】:

我写了一个线程,为了内存同步,我必须使用 Atomcinteger。这是我的代码:

public class NewClass implements Runnable {

public double rr;
public double rmse_new;
public double rmse_newT;
private int k;
private int[][] Xdisc;

public NewClass(int Xdisc[][], double[][] pat_cand, int k, double[][] Yresid, double[][] Xresid) {

    this.k = k;
    this.Xdisc = Xdisc;
}

@Override
public void run() {
    final AtomicInteger q = new AtomicInteger(0);
    q.set(0);
    while (true) {
        if (q.incrementAndGet() >= Xdisc.length) {
            break;

            Integer[] temp_X;
            temp_X = new Integer[Xdisc[0].length];
            for (int s = 0; s < Xdisc[0].length; s++) {
                temp_X[s] = Xdisc[q][s];
            }
        }
    }
}
}

问题是 q 是二维数组 Xdisc(在主类中)的行索引,显然应该是整数,但在 NewClass 中,q 是 AtomicInteger。因此我得到了这个错误:

incompatible types
required: int
found: AtomicInteger

在这一行

temp_X[s] = Xdisc[q][s];

我什至尝试过

temp_X[s] = Xdisc[(int)q][s];

得到了这个错误:

inconvertible types

是否有将 AtomicInteger 转换为 int 的方法?

【问题讨论】:

  • 无论如何,您的代码目前已损坏,因为您在 break 语句之后获得了代码 - 这是无法访问的。当代码以与他的问题无关的方式被破坏时,很难建议工作代码。
  • 看起来你不需要在这里使用原子......你只在单个线程中使用它。原子类和 volatile 用于线程之间共享的值。

标签: java multithreading synchronization


【解决方案1】:

请使用:

AtomicInteger x = new AtomicInteger();
int result = x.intValue();

【讨论】:

    【解决方案2】:

    如果您尝试在整个循环中使用相同的值,只需使用 incrementAndGet() 的返回值:

    int index = q.incrementAndGet();
    if (index >= Xdisc.length) {
        break;
    } // I'm assuming you meant there to be a brace here...
    
    Integer[] temp_X;
    temp_X = new Integer[Xdisc[0].length];
    for (int s = 0; s < Xdisc[0].length; s++) {
        temp_X[s] = Xdisc[index][s];
    }
    

    如果您想要绝对最新值,请使用get()

    【讨论】:

    • 附带说明,在 for 循环中 Xdisc[Xdisc.length] 处有一个数组索引超出范围。 if 条件应该是 if (index &gt;= Xdisc.length - 1) 或简单的 if (index == Xdisc.length - 1)
    • @Radiodef:嗯,我不这么认为。 Xdisc.length - 1 的索引很好,所以当 index 具有该值时,我们仍然应该进行循环。是什么让你认为我们需要早点停下来?
    • 现在 while 循环在 index == Xdisc.length 处停止。循环基本上看起来像while(++index &lt;= Xdisc.length);
    • @Radiodef:是的,确实如此。也就是说,当index == Xdisc.length for 循环 执行时 - 这是正确的,因为 that 会导致异常。但它确实index == Xdisc.length - 1 时执行,这也是正确的,但您建议的代码不会发生这种情况。
    • @Radiodef:不,它看起来不像那个 while 循环 - 因为它在执行 index == Xdisc.length中断,然后执行 for 循环......而你的当index == Xdisc.length 时,while 循环仍然会执行整个主体。
    【解决方案3】:

    Atomic-classes 的目的是允许通过 compareAndSet() 方法或其子方法(如 incrementAndGet())以线程安全的方式使用这些值,但您根本没有在线程上下文中使用 AtomicInteger,所以用标准的 int 替换它不会有任何区别(除了跑得快一点)。

    原因是您在 Runnable 中创建了 AtomicInteger,所以基本上每个线程都会有它的非常自己的实例。

    一般来说,您应该阅读 Java 类的优秀文档,它会回答很多问题:AtomicInteger

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 2019-06-18
      • 1970-01-01
      • 2020-07-03
      • 2012-01-07
      • 1970-01-01
      • 2018-04-28
      • 2011-05-13
      • 1970-01-01
      相关资源
      最近更新 更多