I
I
Ivan Balaksha2014-07-14 21:55:54
Java
Ivan Balaksha, 2014-07-14 21:55:54

How to run 10+ threads in java without repetitive code?

How to run arbitrary number of threads? Now for 5 threads you have to use

Thread t1 = new myThread();
            Thread t2 = new myThread();
            Thread t3 = new myThread();
            Thread t4 = new myThread();
            Thread t5 = new myThread();
            t1.start();
            t2.start();
            t3.start();
            t4.start();
            t5.start();
            t1.join();
            t2.join();
            t3.join();
            t4.join();
            t5.join();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Cheremisin, 2014-07-15
@tagantroy

Something like this....

ArrayList<Thread> mythreads = new ArrayList<Thread>();
int tcount = 1000;
for(int i=0; i< tcount; i++) {
     Thread thr = new myThread();
     mythreads.add(thr);
     thr.start();
}
for (Thread thr : mythreads) {
     thr.joint();
}

or fashionable
ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<5000;i++)
    es.execute(new Runnable() { /*  your task */ });
es.shutdown();
boolean finshed = es.awaitTermination(1, TimeUnit.MINUTES);

F
FlaIDzeres, 2014-07-14
@FlaIDzeres

It seems to me that there is exhaustive information here, tutorials.jenkov.com/java-concurrency/thread-pools.html
Either stupidly the same as what you are doing but in a loop.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question