[英]Multithreading example for x number of threads
我是多线程世界的新手,如果我们从命令提示符处传递x个线程,则不确定如何编写一个可以调用x个线程的java应用程序。 就像我们经过
java –jar pds_client_batch.jar <number of threads>
如果这里传递的线程数为20,则应该运行20个线程。 任何简单的例子将不胜感激。
public class Example
{
private class DumbThread implements Runnable
{
public void run()
{
System.out.println("Thread ran");
}
}
public static void main(String args[])
{
int input = Integer.parseInt(args[0]);
for (int x = 0; x < input; x++)
new Thread(new DumbThread()).start();
}
}
现在,如果您希望它做一些有用的事情...
编辑:更完整。 它仍然没有任何用处。 而且它甚至不进行基本的错误检查。
您也可以像ThreadPoolExecutor这样的executorService。 并传入您要使用的线程数。
如今,鼓励您使用线程池更好地管理线程。 您可以创建一个固定的线程池:
class ThreadTask implements Runnable {
private int id;
public ThreadTask(int id) {
this.id = id;
}
public void run() {
System.out.println("I am task " + id);
}
}
public class TestPool {
public static void main(String[] args) {
int size = Integer.parseInt(args[0]);
// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(size);
// queue some tasks
for(int i = 0; i < 3 * size; i++) {
service.submit(new ThreadTask(i));
}
// wait for termination
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.