简体   繁体   English

Java多线程控制

[英]Java Multi Threading Control

I am using this code to create threads. 我正在使用此代码来创建线程。

      while ((strLine = br.readLine()) != null) {
                r = new runnable(strLine);
                new Thread(r).start();
                x++;
                Thread.sleep(100);
      }

How can I control the maximum number of threads running at any point of time? 如何控制在任何时间点运行的最大线程数? This code has issues where memory used keeps rising(memory leak) is there a better way to do this? 此代码存在使用内存不断上升(内存泄漏)的问题有更好的方法吗? I tried using scheduler but didnt help. 我尝试使用调度程序,但没有帮助。

You can use an ExecutorService to create constrained thread pools. 您可以使用ExecutorService创建受约束的线程池。

ExecutorService executor = Executors.newFixedThreadPool(10);

will create a pool with 10 available threads. 将创建一个包含10个可用线程的池。 You can then call 然后你可以打电话

executor.submit(new Runnable() { ... })

for each unit of work. 对于每个工作单元。

EDIT : I should note that this facility is only available in Java 1.5 and later. 编辑 :我应该注意,此工具仅适用于Java 1.5及更高版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM