English 中文(简体)
java 串行不同的串流 [关闭]
原标题:java threads different streams [closed]

此代码读取来自不同蒸汽数据的数字, 并输出整个总和。 这个代码有什么问题吗? 我如何修正它?

public class Thr extends Thread{
static int numThr=100, sum=0;
private int num;
private Thr(int num){this.num =num;}
public void run() {
    int k = IntegerReader.get(num);
    int count=0;
    while(k>0) {
        if(count%numThr==num) sum+=k;
        count++;
        k=IntegerReader.get(num);
    }
}
public static void main(String[] a) throws Exception {
    thr[] st =new thr[numThr];
    for(int i=0; i<numThr; i++) st[i] = new Thr(i);
    for(int i=0; i<numThr; i++) st[i].start();
    System.out.println("sum = "+sum);
}
}
最佳回答

球棒上有许多错误的东西

  1. 共和在多个线条之间共享,在多个线条中增加值,这意味着你可以得到不一致的值,因为递增值不是原子操作。

    The easiest fix for this is change the declaration of sum to: private static AtomicInteger sum = new AtomicInteger(0);

    and add to it this way: sum.getAndAdd(k)

  2. “ numThr” 由多个线索共享, 由多个线索读取。 由于 numThr 不是最终线索、 同步或波动, 无法保证其他线索会看到其值已经初始化 。 numThr 应该被宣布为 < code> 私人静态最终numThr=100

  3. 您的 < code> System. out. primpln (“ sum ” = “ +sum ”); 将会在您的线条完成执行之前打印。 您需要先在您的线条上“ 加入 ” (即等待它们完成) 才能打印 。 添加 : < code> for (int i=0; i< numThr; i++) st[i]. join (); before your sysout.

I think you should read up on the Java Memory Model and concurrency in Java. Here is a basic tutorial, but you really need a book on the subject: http://docs.oracle.com/javase/tutorial/essential/concurrency/

问题回答

是的,这个代码有几种错误。 修正它的一种方法是花时间阅读和理解一个 < a href=" http://docs. oracle.com/javase/tuvase/" rel="nofollow" > Java controduction 。 另一种方法是请别人帮你修, 但请注意, 某类东西不会在这里得到很好的处理 。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签