Concurrency in thread creation and execution
Hi Experts,
I want a separate class that would manage thread creation.. also, Main class will take a parameter that is how many threads can run in parallel… if I have 10 objects but 4 threads then 5th one should start only after one of the first 4 is complete.. and so on.
Can anybody help me ..how to implement such kind of scenario.
I have attached a sample code which will create 10 thread and runs in parallel, But i need it little different , thread will be create by another class and Main class will take only 4 thread at a time.
After finishing 4th one 5th thread will start.
Bellow is the code:::
class MyRunnable implements Runnable {
int name;
MyRunnable(int i) {
name = i;
System.out.println("Thraed:" +name);
}
public void run() {
try {
for (int j = 0; j < 3; j++) {
System.out.println( name + " : " + " " +j);
Thread.sleep(100);
}
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
{
Runnable task = new MyRunnable(i);
Thread worker = new Thread(task);
worker.start();
}
}
}