jackcogdill
jackcogdill

Reputation: 5122

How do I slow down the generation of Threads in java?

I am spawning 20 threads (they are all supposed to be running at the same time). However, they are all created at the same time and all start running at the same time, which gives the entire program major lag (this is lag, my computer is not slow).

So, I want to have them created at different times, e.g. generate one every 2 seconds or so. How do I do this? I have tried using a ton of stuff but none of it works the way I want it to. I have tried using boolean methods to not loop again until it is true, but this doesn't seem to work. Any ideas?

for (int i = 0; i < 20; i++) {
    Rain r = new Rain();
    r.start();
}

Upvotes: 2

Views: 292

Answers (4)

Tim Pote
Tim Pote

Reputation: 28029

If you are experiencing lag due to the number of threads you are creating, the best solution is probably to lower the number of threads you are creating.

Also, Java 5 introduced the executor service framework, Which was improved again in Java 7 with fork/joins, so you shouldn't have to be creating threads yourself at all under normal circumstances. (Here is a link to a page with a pretty good explanation of those concepts.)

I generally don't start more threads than I have cores on the machine, like so:

int availableThreads = Runtime.getRuntime().availableProcessors();
ExecutorService executorService = Executors.newFixedThreadPool(availableThreads);

// ...Create List<Future<ReturnObject>>
// populate list by calling futures.add(executorService.submit(callable));

executorService.shutdown();

This is because, as long as the process in computationally intensive, your biggest threading gains are made when you have simultaneous computation on each core instead of thread switching on a single core. Of course, that changes when you're talking about a process that's disk or network intensive, but it's a pretty good rule of thumb.

Upvotes: 2

Henrik Karlsson
Henrik Karlsson

Reputation: 5713

You could probably just create a spawner thread, which just sleeps 2 seconds between spawning each thread:

for (int i = 0; i < 20; i++) {
    Rain r = new Rain();
    r.start();
    Thread.sleep(2000);
}

Note: Left out try-catch blocks

Upvotes: 3

evanwong
evanwong

Reputation: 5134

I don't really see why it will be lagged for only 20 threads creating but you can put a sleep if you want them to be started at different time:

for (int i = 0; i < 20; i++) {
    Rain r = new Rain();
    r.start();
    Thread.sleep(2000);
}

Upvotes: 1

kevingreen
kevingreen

Reputation: 1541

Try running the thread generator as a thread, then implement a Thread.sleep(2000)

Upvotes: 4

Related Questions