codetoad.com
  ASP Shopping CartForum & BBS
  - all for $20 from CodeToad Plus!
  
  Home || ASP | ASP.Net | C++/C# | DHTML | HTML | Java | Javascript | Perl | VB | XML || CodeToad Plus! || Forums || RAM 
Search Site:
Search Forums:
  Multithreading----- Please help anyone  Camille_83 at 22:46 on Thursday, June 08, 2006
 

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.


  Re: Multithreading----- Please help anyone  crwood at 20:48 on Saturday, June 10, 2006
 

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);
}
}









CodeToad Experts

Can't find the answer?
Our Site experts are answering questions for free in the CodeToad forums








Recent Forum Threads
•  Transfer of selected row data from 1 table to another table - Need help
•  Re: New to C++, can anyone help me out?
•  Re: power
•  Connecting to a Access data base using javascript
•  Drag and Drop image
•  Re: Multithreading----- Please help anyone
•  DHTML Popup Tooltip Script. How to add sound?
•  Sorting in ascending - random characters from user
•  problems with onload


Recent Articles
What is a pointer in C?
Multiple submit buttons with form validation
Understanding Hibernate ORM for Java/J2EE
HTTP screen-scraping and caching
a javascript calculator
A simple way to JTable
Java Native Interface (JNI)
Parsing Dynamic Layouts
MagicGrid
Caching With ASP.Net


© Copyright codetoad.com 2001-2006