[英]Java Threads (Am I doing this correctly?)
我想创建并启动5个Java线程。 线程应显示消息,然后停止执行。 我是否正确执行此操作?
public class HelloThread extends Thread {
private String thread_name;
// constructor
HelloThread(String tname) {
thread_name = new String(tname);
}
// override method run()
public void run() {
setName(thread_name);
System.out.println(" Thread " + thread_name); //assigning each thread a name
}
public static void main(String args[]) {
for (int i = 1; i < 6; i++) {
HelloThread mythr_obj = new HelloThread(i + " says Hello World!!! ");
mythr_obj.start(); // start execution of the thread object
}
}
}
自从Java 1.4 java.util.concurrent
引入java.util.concurrent
库以来,开发人员这些天很少创建自己的Thread
实例。
今天,您更有可能
ExecutorService threadPool = Executors.newFixedThreadPool(5);
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 20; ++ i) {
Callable<Integer> callable = () -> {
TimeUnit.SECONDS.sleep(1);
System.out.println("Returning " + i);
return i;
};
Future<Integer> future = threadPool.submit(callable);
futures.add(future);
}
for (Future<Integer> future : futures) {
Integer result = future.get();
System.out.println("Finished " + result);
}
threadPool.shutdown();
您是否尝试过编译并运行此代码? 看起来正确,尽管我建议您将main
方法放在单独的类中。
是。 您做得不错,但正如@FSQ所建议的那样,您的整个类本身就是一个线程。 您可以将main方法放在任何其他类中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.