简体   繁体   中英

spawn X threads per second in java

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

Put the thread generation in timer or alike. Eg

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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