java - 简单的Java并发线程——捕获开始和结束

标签 java multithreading

我是否正确实现了这些 Java 线程?目标是有 10 个并发线程计算从 1 到(上限 22 + i)的总和。我试图识别名称并在运行线程时打印它,然后在线程退出时打印结果。目前,我以随机顺序同时打印所有结果,并且我不确定线程​​开始和结束时是否正确获取信息。

public class threads {
  public static void main(String[] args) {
    for(int i = 0; i < 10; i++) {
      final int iCopy = i;
      new Thread("" + i) {
        public void run() {
          int sum = 0;
          int upperBound = 22;
          int lowerBound = 1;
          long threadID = Thread.currentThread().getId();

          for (int number = lowerBound; number <= upperBound; number++){
            sum = sum + number + iCopy;

          }
          System.out.println(threadID + " thread is running now, I and will compute the sum from 1 to " + (upperBound + iCopy) + ". The i is : " + iCopy);
          System.out.println("Thread id #" + threadID + ", the "+ sum + " is done by the thread.");
        }

      }.start();
    }
  }
}

最佳答案

我已经执行了您的代码,并观察到在这种情况下所有线程都正常运行 10。由于线程是以随机顺序调用的,这就是为什么可能会看到这种行为,但我确信所有线程都可以正常运行并执行您所需的功能。

在输出中我看到 for 循环中的值应该从 0 到 9 开始,但这里即使这是随机的,可能是因为某些线程在执行时正在 hibernate 并让位于其他线程。

希望这有帮助 谢谢。

关于java - 简单的Java并发线程——捕获开始和结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26581372/

相关文章:

java - 如何本地化 GWT 客户端代码中的枚举值?

java - JAVA中通过JACOB读取BSTR

node.js - NodeJS集群: how to reduce data from workers in master?

python - wx.lib.editor 中的线程

java - 线程在进程级别同时工作?

java - 如何忽略 Eclipse 中的换行?

java - TestNG:并行线程运行类安全吗?

java - 在java中迭代之前删除元素列表

java - JTree 给出 ArrayIndexOutOfBoundsException?

java - Unix:删除文件代码给出一些过程