|
Can some please help to write an application in Java that creates a thread pool of 3 or more threads. Each of the threads should generate a random # between 1 and 50, print out the thread name & the random # & add the random # to a vector. After each thread has added a # to the vector, print out the vector & the sum of the # in the vector.
|
|
|
This is mostly copied from the tutorial page Thread Pools. The api has code snippets too, eg, Executor.
import java.util.*;
import java.util.concurrent.*;
public class ThreadPoolTest
{
public static void main(String[] args)
{
Vector<Integer> vector = new Vector<Integer>();
int numberOfWorkers = 4;
int threadPoolSize = 2;
ExecutorService pool = Executors.newFixedThreadPool(threadPoolSize);
WorkerThread[] workers = new WorkerThread[numberOfWorkers];
Future[] futures = new Future[numberOfWorkers];
for(int j = 0; j < workers.length; j++)
{
workers[j] = new WorkerThread(j, vector);
futures[j] = pool.submit(workers[j]);
}
for(int j = 0; j < workers.length; j++)
{
try
{
futures[j].get();
}
catch(Exception e) { }
}
pool.shutdown();
System.out.println("vector = " + vector);
int sum = 0;
for(int j = 0; j < vector.size(); j++)
sum += ((Integer)vector.get(j)).intValue();
System.out.println("sum = " + sum);
}
}
class WorkerThread implements Runnable
{
int id;
Vector<Integer> vector;
Random r;
public WorkerThread(int id, Vector<Integer> v)
{
this.id = id;
vector = v;
r = new Random();
}
public void run()
{
int n = 1 + r.nextInt(50);
vector.add(new Integer(n));
System.out.printf("Worker id %d, n = %d\n", id, n);
}
}
|
|
|
|
|
|
|
|
|
|