Java 关于简单线程示例输出的查询
我正在尝试开始学习Java中的线程,下面是一个简单的示例 这是我的密码: 一个简单的主类:Java 关于简单线程示例输出的查询,java,multithreading,Java,Multithreading,我正在尝试开始学习Java中的线程,下面是一个简单的示例 这是我的密码: 一个简单的主类: 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 c
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);
}
}
但是,我不明白为什么Main.java中标有注释A的行从未打印出来。对此的任何见解都会有所帮助。
谢谢 就最佳实践而言,该代码存在一些错误。除非这个网站提到他们(懒得看),我可能会考虑找一个不同的教程。另外,您是否检查了整个输出?可能是印刷品。它不能保证像我猜想的那样作为最后一件事打印出来。从最佳实践的角度来看,该代码有一些地方是错误的。除非这个网站提到他们(懒得看),我可能会考虑找一个不同的教程。另外,您是否检查了整个输出?可能是印刷品。它不能保证像我猜的那样作为最后一件事打印出来。它应该打印出来。检查您是否在程序输出中丢失了它。
试着在您的Runnable中注释println(),它应该打印出来。检查您是否在程序输出中丢失了它。
试着在你的Runnable中注释println(),它应该可以打印一些东西。关于测试的一些想法:
- 在runnable中对println语句进行注释-可能会打印出来,但您看不到它,因为控制台上有太多的输出
- 在
语句之前添加一个do
,查看添加了多少线程(应打印500个)System.println(threads.size())
- 在
语句之前添加do
。可能第一个线程在do while块完成后激活Thread.sleep(100)
- 在runnable中对println语句进行注释-可能会打印出来,但您看不到它,因为控制台上有太多的输出
- 在
语句之前添加一个do
,查看添加了多少线程(应打印500个)System.println(threads.size())
- 在
语句之前添加do
。可能第一个线程在do while块完成后激活Thread.sleep(100)
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...