Reputation: 3626
I wanna achieve spawning 1000 threads per second. This is how I am doing it now :
public class Client {
private static final int NTHREDS = 1000;
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
for (int i = 0; i < 1000; i++) {
Runnable worker = new MyTask();
executor.execute(worker);
}
executor.shutdown();
System.out.println("Finished all threads");
}
}
MyTask looks like this:
public class MyTask implements Runnable{
@Override
public void run() {
execute();
}
}
In my example, the spawning doesnt happen per second, its just a for loop which sequentially spawns 1000 threads. Is there a better way to achieve X threads / second ?
Thanks
Upvotes: 0
Views: 836
Reputation: 86
Put the thread generation in timer or alike. E.g.
final ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
executor.execute(new MyTask());
}
}, 0, 1, TimeUnit.MILLISECONDS);
Upvotes: 4