Reputation: 9384
I have a class,which implements Runnable
interface. I want to create multiple threads for that class and I have found two approaches for creating a multithread:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Important job running in MyRunnable");
}
}
1.first approach:
public class TestThreads {
public static void main (String [] args) {
MyRunnable r = new MyRunnable();
Thread foo = new Thread(r);
Thread bar = new Thread(r);
Thread bat = new Thread(r);
foo.start();
bar.start();
bat.start();
}
}
2.second approach:
public class TestThreads
{
public static void main (String [] args)
{
Thread[] worker=new Thread[3];
MyRunnable[] r = new MyRunnable[3];
for(int i=0;i<3;i++)
{
r[i] = new MyRunnable();
worker[i]=new Thread(r[i]);
worker[i].start();
}
}
}
Which one is best approach to use and what is difference between both?
Regards
Upvotes: 1
Views: 5192
Reputation: 62439
Well each one of the two approaches has their use:
Upvotes: 0
Reputation: 21186
Only difference is the first one there is only one copy of "MyRunnable" that is run 3 times. 2nd approach each thread has its own copy of MyRunnable. Not a problem in this case as
Upvotes: 0
Reputation: 35604
In your example the runnable has not instance state, so you don't need multiple instances of it.
Otherwise I like the second approach more, because every time you cut&paste a line of codemultiple times in a row, a loop usually is the better idea.
And usually, you should wait for a thread you started.
public class TestThreads {
public static void main (String [] args) {
Thread[] worker=new Thread[3];
Runnable r = new MyRunnable();
for(int i=0;i<3;i++) {
worker[i]=new Thread(r);
worker[i].start();
}
for(int i=0;i<3;i++) {
worker[i].join();
worker[i] = null;
}
}
}
The next step then would be using the ExecutorService of Java 5+. You don't want and need to manage you own thread in modern Java.
int poolSize = 3;
int jobCount = 3;
Runnable r = new MyRunnable()
ExecutorService pool = Executors.newFixedThreadPool(poolSize);
for (int i = 0; i < jobCount; i++) {
pool.execute(r);
}
pool.shutdown();
Upvotes: 2