查询有关简单Thread示例的输出

时间:2012-03-06 06:50:52

标签: java multithreading

我正在尝试开始学习Java中的线程,这是我从here尝试的一个简单示例 这是我的代码:  一个简单的主要类:

    package com.vogella.Thread;

  import java.util.ArrayList;
 import java.util.List;

      public class Main {
public static void main(String[] args) {
    // We will store the threads so that we can check if they are done
    List<Thread> threads = new ArrayList<Thread>();
    // We will create 500 threads
    for (int i = 0; i < 500; i++) {
        Runnable task = new MyRunnable(10000000L + i);
        Thread worker = new Thread(task);
        // We can set the name of the thread
        worker.setName(String.valueOf(i));
        // Start the thread, never call method run() direct
        worker.start();
        // Remember the thread for later usage
        threads.add(worker);
    }
    int running = 0;

    do {
        running = 0;
        for (Thread thread : threads) {
            if (thread.isAlive()) {
                running++;
            }
        }
        System.out.println("We have " + running + " running threads. ");//-A
    } while (running > 0);

}
}

和MyRunnable类如下:

package com.vogella.Thread;

public class MyRunnable implements Runnable {
private final long countUntil;

MyRunnable(long countUntil) {
    this.countUntil = countUntil;
}
@Override
public void run() {
    long sum = 0;
    for (long i = 1; i < countUntil; i++) {

        sum += i;
    }
    System.out.println(sum);
    System.out.println("Test123");
}

} 这是我的输出

  49999995000000
   Test123
   50000005000000
  Test123
  50000015000001
   Test123...

但是我不明白为什么Main.java中标有评论A 的行永远不会打印出来。对此有任何见解会有所帮助。 谢谢!

3 个答案:

答案 0 :(得分:2)

在最佳做法方面,该代码存在一些问题。除非该网站提到它们(懒得看),我可能会考虑找一个不同的教程。还有,你检查了整个输出?它可能是印刷品。我不能保证打印出最后的东西,因为我猜你正在假设。

答案 1 :(得分:2)

应该打印。检查您是否在程序输出中没有遗漏它。 尝试在Runnable

中注释掉println()

答案 2 :(得分:0)

应该可以打印一些东西。一些测试的想法:

  • 评论你的runnable中的println语句 - 也许得到打印但是你没有看到它,因为控制台上的输出太多了
  • System.println(threads.size())语句前添加do以查看已添加的线程数(应打印500个)。
  • Thread.sleep(100)语句前添加do。也许第一个线程在 do-while块完成后生效了......