Reputation: 27
I'm very new to threads. I need to implement such method, which will create 2 threads, do something and then kill them - everything inside the for loop.
Main purpose : I need to be SURE that threads will work parallel with the same "i" value from for loop. That's why I do not declare for loop inside every thread. (which one finish first I do not care)
My vision
public void threadsJob() throws Exception{
for(int i = 1; i<1000 ; i++) {
**final** int j = i;
Thread t1= new Thread(new Runnable() {
public void run() {
foo(j);
}
}
);
Thread t2= new Thread(new Runnable() {
public void run() {
bar(j);
}
}
);
t1.start();
t2.start();
t1.join();
t2.join();
}}
My question : how horrible is that code? what should be changed ? Also I prefer to keep code quite simple. However, Im not sure if above code is suitable example :)
Upvotes: 1
Views: 144
Reputation: 3414
Use Executors.newFixedThreadPool(2)
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html
Execute two Runnables that perform your work.
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
Then shutdown and awaitTermination on the ExecutorService.
Upvotes: 2