开发者

Java Multi Threading Control

开发者 https://www.devze.com 2023-03-07 16:26 出处:网络
I am using this code to create threads. while开发者_运维技巧 ((strLine = br.readLine()) != null) {

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 executor = Executors.newFixedThreadPool(10);

will create a pool with 10 available threads. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消