First of all my code try to multiply a 2D array the idea is that i want to calculate each element with new thread and at last i want to measure the time that it will take but when i want to do that for a large size of arrays, the "system.out.println()" instruction doesn't print anything, and here it is my code:
////// calcSerial class
package Solutions;
import java.util.Random;
public class CalcSerial {
public static int[][] initializeMatrixRandom(int row, int col){
int[][] mat = new int[row][col];
Random random = new Random();
for(int i=0; i<row;i++) {
for(int j=0;j<col;j++) {
mat[i][j] = random.nextInt(10);
}
}
return mat;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int row = 4000;
int column = 4000;
int[][] A = initializeMatrixRandom(row, column);
int[][] B = initializeMatrixRandom(column, row);
long startTime = System.nanoTime();
OneThreadCalc [][]otc = new OneThreadCalc[A.length][B[0].length];
int[][] res = new int[A.length][B[0].length];
for(int i=0;i< A.length;i++) {
for(int j=0;j<B[0].length;j++) {
otc[i][j] = new OneThreadCalc(i, j, A, B);
otc[i][j].start();
}
}
for(int i=0;i< A.length;i++)
{
for(int j=0;j<B[0].length;j++) {
try{
otc[i][j].join();
}catch(Exception e){}
}
}
for(int i=0;i< A.length;i++) {
for(int j=0;j<B[0].length;j++) {
res[i][j] = 0;
res[i][j] = otc[i][j].getElement();
}
}
long endTime = System.nanoTime();
long totalTime = (endTime - startTime)/1000000000;
System.out.println("Program took "+ totalTime + "s.");
}
}
////// And the OneThreadCalc class is : /////////
package Solutions;
public class OneThreadCalc extends Thread{
int i;
int j;
int A[][];
int B[][];
int res = 0;
OneThreadCalc(int i, int j, int A[][], int B[][]){
this.i = i;
this.j = j;
this.A = A;
this.B = B;
}
public void run() {
int colA = A[0].length;
for(int k=0;k<colA;k++) {
res += A[i][k]*B[k][j];
}
}
public int getElement() {
return res;
}
}
I have following the code that loop through array list(mainItems) and find the most similar two arrays and put them in sortedTransactions. It is working fine for small data (10000 transactions) but it is running forever for 88000 transactions. What can be done to make it work for big data.
import java.util.*;
public class Sort {
static private List<Transactions> trans = ReadFile.transactions;
static public List<int[]> mainItems;
static public ArrayList<int[]> sortedTransactions = new ArrayList<int[]>();
static {
mainItems = new ArrayList<int[]>();
for (Transactions t : trans) {
mainItems.add(t.getItems());
}
}
static private double jaccardSimilarity(int[] a, int[] b) {
Set<Integer> s1 = new LinkedHashSet<Integer>();
for(int i =0; i< a.length; i++){
s1.add(a[i]);
}
Set<Integer> s2 = new LinkedHashSet<Integer>();
for(int i =0; i< b.length; i++){
s2.add(b[i]);
}
Set<Integer> intersection = new LinkedHashSet<>(s1);
intersection.retainAll(s2);
Set<Integer> union = new LinkedHashSet<Integer>(s1);
union.addAll(s2);
double jaccardSimilarity = (double)intersection.size()/ (double)union.size();
//System.out.println(intersection);
return jaccardSimilarity;
}
static private boolean isAllEqual(List<Double> a){
for(int i=1; i<a.size(); i++){
if(a.get(0) != a.get(i)){
return false;
}
}
return true;
}
static public void generatePairs() {
for (int i = 0; i < mainItems.size() - 1; i++) {
if (!sortedTransactions.contains(mainItems.get(i))) {
List<Double> myd = new ArrayList<Double>();
List<int[]> mys = new ArrayList<int[]>();
for (int j = i + 1; j < mainItems.size(); j++) {
if (!sortedTransactions.contains(mainItems.get(j))) {
myd.add(jaccardSimilarity(mainItems.get(i),mainItems.get(j)));
mys.add(mainItems.get(j));
}
}
if (isAllEqual(myd) == false) {
sortedTransactions.add(mainItems.get(i));
sortedTransactions.add(mys.get(maxValue(myd)));
}
}
}
}
static private int maxValue(List<Double> d) {
double max = d.get(0);
int f = 0;
for(int i =1; i< d.size(); i++){
if(d.get(i) > max){
max= d.get(i);
f= i;
}
}
return f;
}
}
You don't have to create the union set (union(s1, s2).size() is s1.size() + s2.size() - intersection(s1, s2).size()).
static private double jaccardSimilarity(int[] a, int[] b) {
Set<Integer> s1 = new HashSet<Integer>();
for (int i = 0; i < a.length; i++) {
s1.add(a[i]);
}
Set<Integer> s2 = new HashSet<Integer>();
for (int i = 0; i < b.length; i++) {
s2.add(b[i]);
}
final int sa = s1.size();
final int sb = s2.size();
s1.retainAll(s2);
final int intersection = s1.size();
return 1d / (sa + sb - intersection) * intersection;
}
I'm trying to create a Java program with threads for matrix multiplication. This is the source code:
import java.util.Random;
public class MatrixTest {
//Creating the matrix
static int[][] mat = new int[3][3];
static int[][] mat2 = new int[3][3];
static int[][] result = new int[3][3];
public static void main(String[] args) {
//Creating the object of random class
Random rand = new Random();
//Filling first matrix with random values
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
mat[i][j] = rand.nextInt(10);
}
}
//Filling second matrix with random values
for (int i = 0; i < mat2.length; i++) {
for (int j = 0; j < mat2[i].length; j++) {
mat2[i][j] = rand.nextInt(10);
}
}
try {
//Object of multiply Class
Multiply multiply = new Multiply(3, 3);
//Threads
MatrixMultiplier thread1 = new MatrixMultiplier(multiply);
MatrixMultiplier thread2 = new MatrixMultiplier(multiply);
MatrixMultiplier thread3 = new MatrixMultiplier(multiply);
//Implementing threads
Thread th1 = new Thread(thread1);
Thread th2 = new Thread(thread2);
Thread th3 = new Thread(thread3);
//Starting threads
th1.start();
th2.start();
th3.start();
th1.join();
th2.join();
th3.join();
} catch (Exception e) {
e.printStackTrace();
}
//Printing the result
System.out.println("\n\nResult:");
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}//End main
}//End Class
//Multiply Class
class Multiply extends MatrixTest {
private int i;
private int j;
private int chance;
public Multiply(int i, int j) {
this.i = i;
this.j = j;
chance = 0;
}
//Matrix Multiplication Function
public synchronized void multiplyMatrix() {
int sum = 0;
int a = 0;
for (a = 0; a < i; a++) {
sum = 0;
for (int b = 0; b < j; b++) {
sum = sum + mat[chance][b] * mat2[b][a];
}
result[chance][a] = sum;
}
if (chance >= i)
return;
chance++;
}
}//End multiply class
//Thread Class
class MatrixMultiplier implements Runnable {
private final Multiply mul;
public MatrixMultiplier(Multiply mul) {
this.mul = mul;
}
#Override
public void run() {
mul.multiplyMatrix();
}
}
I just tried on Eclipse and it works, but now I want to create another version of that program in which, I use one thread for each cell that I'll have on the result matrix. For example I've got two 3x3 matrices. So the result matrix will be 3x3. Then, I want to use 9 threads to calculate each one of the 9 cells of the result matrix.
Can anyone help me?
You can create n Threads as follows (Note: numberOfThreads is the number of threads that you want to create. This will be the number of cells):
List<Thread> threads = new ArrayList<>(numberOfThreads);
for (int x = 0; x < numberOfThreads; x++) {
Thread t = new Thread(new MatrixMultiplier(multiply));
t.start();
threads.add(t);
}
for (Thread t : threads) {
t.join();
}
Please use the new Executor framework to create Threads, instead of manually doing the plumbing.
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreadsInPool);
for (int i = 0; i < numberOfThreads; i++) {
Runnable worker = new Thread(new MatrixMultiplier(multiply));;
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
With this code i think that i resolve my problem. I don't use synchronized in the methods but i think that is not necessary in that case.
import java.util.Scanner;
class MatrixProduct extends Thread {
private int[][] A;
private int[][] B;
private int[][] C;
private int rig, col;
private int dim;
public MatrixProduct(int[][] A, int[][] B, int[][] C, int rig, int col, int dim_com) {
this.A = A;
this.B = B;
this.C = C;
this.rig = rig;
this.col = col;
this.dim = dim_com;
}
public void run() {
for (int i = 0; i < dim; i++) {
C[rig][col] += A[rig][i] * B[i][col];
}
System.out.println("Thread " + rig + "," + col + " complete.");
}
}
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner In = new Scanner(System.in);
System.out.print("Row of Matrix A: ");
int rA = In.nextInt();
System.out.print("Column of Matrix A: ");
int cA = In.nextInt();
System.out.print("Row of Matrix B: ");
int rB = In.nextInt();
System.out.print("Column of Matrix B: ");
int cB = In.nextInt();
System.out.println();
if (cA != rB) {
System.out.println("We can't do the matrix product!");
System.exit(-1);
}
System.out.println("The matrix result from product will be " + rA + " x " + cB);
System.out.println();
int[][] A = new int[rA][cA];
int[][] B = new int[rB][cB];
int[][] C = new int[rA][cB];
MatrixProduct[][] thrd = new MatrixProduct[rA][cB];
System.out.println("Insert A:");
System.out.println();
for (int i = 0; i < rA; i++) {
for (int j = 0; j < cA; j++) {
System.out.print(i + "," + j + " = ");
A[i][j] = In.nextInt();
}
}
System.out.println();
System.out.println("Insert B:");
System.out.println();
for (int i = 0; i < rB; i++) {
for (int j = 0; j < cB; j++) {
System.out.print(i + "," + j + " = ");
B[i][j] = In.nextInt();
}
}
System.out.println();
for (int i = 0; i < rA; i++) {
for (int j = 0; j < cB; j++) {
thrd[i][j] = new MatrixProduct(A, B, C, i, j, cA);
thrd[i][j].start();
}
}
for (int i = 0; i < rA; i++) {
for (int j = 0; j < cB; j++) {
try {
thrd[i][j].join();
} catch (InterruptedException e) {
}
}
}
System.out.println();
System.out.println("Result");
System.out.println();
for (int i = 0; i < rA; i++) {
for (int j = 0; j < cB; j++) {
System.out.print(C[i][j] + " ");
}
System.out.println();
}
}
}
Consider Matrix.java and Main.java as follows.
public class Matrix extends Thread {
private static int[][] a;
private static int[][] b;
private static int[][] c;
/* You might need other variables as well */
private int i;
private int j;
private int z1;
private int s;
private int k;
public Matrix(int[][] A, final int[][] B, final int[][] C, int i, int j, int z1) { // need to change this, might
// need some information
a = A;
b = B;
c = C;
this.i = i;
this.j = j;
this.z1 = z1; // a[0].length
}
public void run() {
synchronized (c) {
// 3. How to allocate work for each thread (recall it is the run function which
// all the threads execute)
// Here this code implements the allocated work for perticular thread
// Each element of the resulting matrix will generate by a perticular thread
for (s = 0, k = 0; k < z1; k++)
s += a[i][k] * b[k][j];
c[i][j] = s;
}
}
public static int[][] returnC() {
return c;
}
public static int[][] multiply(final int[][] a, final int[][] b) {
/*
* check if multipication can be done, if not return null allocate required
* memory return a * b
*/
final int x = a.length;
final int y = b[0].length;
final int z1 = a[0].length;
final int z2 = b.length;
if (z1 != z2) {
System.out.println("Cannnot multiply");
return null;
}
final int[][] c = new int[x][y];
int i, j;
// 1. How to use threads to parallelize the operation?
// Every element in the resulting matrix will be determined by a different
// thread
// 2. How may threads to use?
// x * y threads are used to generate the result.
for (i = 0; i < x; i++)
for (j = 0; j < y; j++) {
try {
Matrix temp_thread = new Matrix(a, b, c, i, j, z1);
temp_thread.start();
// 4. How to synchronize?
// synchronized() is used with join() to guarantee that the perticular thread
// will be accessed first
temp_thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return Matrix.returnC();
}
}
You can use Main.java to give 2 matrices that need to be multiplied.
class Main {
public static int[][] a = {
{1, 1, 1},
{1, 1, 1},
{1, 1, 1}};
public static int[][] b = {
{1},
{1},
{1}};
public static void print_matrix(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++)
System.out.print(a[i][j] + " ");
System.out.println();
}
}
public static void main(String[] args) {
int[][] x = Matrix.multiply(a, b);
print_matrix(x); // see if the multipication is correct
}
}
In simple terms, what you all need to do is,
1) Create n (no of cells in resultant matrix) threads. Assign their roles. (Ex: Consider M X N, where M and N are matrices. 'thread1' is responsible for the multiplication of M's row_1 elements with N's column_1 elements and storing the result. This is the value for the resultant matrix's cell_1.)
2) Start each thread's process. (by start() method)
3) Wait until all the threads finish their processes and store the resultant value of each cell. Because those processes should be finished before displaying the resultant matrix. (You can do this by join() methods, and other possibilities too)
4) Now, you can display the resultant matrix.
Note:
1) Since, in this example, the shared resources (M and N) are only used to read only purpose, you don't need to use 'synchronized' methods to access them.
2) You can see, in this program, there are a group of threads running and all of them needs to achieve a specific status by their own, before continuing the next step of the whole program. This multi-threaded programming model is known as a Barrier.
Tried below code in eclipse as per thread for each cell. It works fine, you can check it.
class ResMatrix {
static int[][] arrres = new int[2][2];
}
class Matrix {
int[][] arr = new int[2][2];
void setV(int v) {
//int tmp = v;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
arr[i][j] = v;
v = v + 1;
}
}
}
int[][] getV() {
return arr;
}
}
class Mul extends Thread {
public int row;
public int col;
Matrix m;
Matrix m1;
Mul(int row, int col, Matrix m, Matrix m1) {
this.row = row;
this.col = col;
this.m = m;
this.m1 = m1;
}
public void run() {
//System.out.println("Started Thread: " + Thread.currentThread().getName());
int tmp = 0;
for (int i = 0; i < 2; i++) {
tmp = tmp + this.m.getV()[row][i] * this.m1.getV()[i][col];
}
ResMatrix.arrres[row][col] = tmp;
System.out.println("Started Thread END: " + Thread.currentThread().getName());
}
}
public class Test {
//static int[][] arrres =new int[2][2];
public static void main(String[] args) throws InterruptedException {
Matrix mm = new Matrix();
mm.setV(1);
Matrix mm1 = new Matrix();
mm1.setV(2);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
Mul mul = new Mul(i, j, mm, mm1);
mul.start();
// mul.join();
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.println("VALUE: " + ResMatrix.arrres[i][j]);
}
}
}
}
In my solution I assigned to each worker a number of rows numRowForThread equals to: (number of rows of matA) / (number of threads).
public class MatMulConcur {
private final static int NUM_OF_THREAD = 1;
private static Mat matC;
public static Mat matmul(Mat matA, Mat matB) {
matC = new Mat(matA.getNRows(), matB.getNColumns());
return mul(matA, matB);
}
private static Mat mul(Mat matA, Mat matB) {
int numRowForThread;
int numRowA = matA.getNRows();
int startRow = 0;
Worker[] myWorker = new Worker[NUM_OF_THREAD];
for (int j = 0; j < NUM_OF_THREAD; j++) {
if (j < NUM_OF_THREAD - 1) {
numRowForThread = (numRowA / NUM_OF_THREAD);
} else {
numRowForThread = (numRowA / NUM_OF_THREAD) + (numRowA % NUM_OF_THREAD);
}
myWorker[j] = new Worker(startRow, startRow + numRowForThread, matA, matB);
myWorker[j].start();
startRow += numRowForThread;
}
for (Worker worker : myWorker) {
try {
worker.join();
} catch (InterruptedException e) {
}
}
return matC;
}
private static class Worker extends Thread {
private int startRow, stopRow;
private Mat matA, matB;
public Worker(int startRow, int stopRow, Mat matA, Mat matB) {
super();
this.startRow = startRow;
this.stopRow = stopRow;
this.matA = matA;
this.matB = matB;
}
#Override
public void run() {
for (int i = startRow; i < stopRow; i++) {
for (int j = 0; j < matB.getNColumns(); j++) {
double sum = 0;
for (int k = 0; k < matA.getNColumns(); k++) {
sum += matA.get(i, k) * matB.get(k, j);
}
matC.set(i, j, sum);
}
}
}
}
}
where for the class Mat, I used this implementation:
public class Mat {
private double[][] mat;
public Mat(int n, int m) {
mat = new double[n][m];
}
public void set(int i, int j, double v) {
mat[i][j] = v;
}
public double get(int i, int j) {
return mat[i][j];
}
public int getNRows() {
return mat.length;
}
public int getNColumns() {
return mat[0].length;
}
}
I would like to simulate a situation which is mentioned in books about concurrency - that without a proper synchronization one thread can see a stale value of a variable that has been already modified by a different thread. This could happen because for example a CPU cache.
To do this I have written the following program. The idea is that there are 4 threads that initialize a different part of a shared array. The 5th thread (main, parent thread) waits until all 4 previous threads are done, iterates over the shared array and adds its values (always 1 or if I'm lucky null, which would mean a stale value)
package p1;
class ArrFill implements Runnable {
int l, r;
Integer[] arr;
ArrFill(int l, int r, Integer[] arr) {
this.l = l;
this.r = r;
this.arr = arr;
}
#Override
public void run() {
for(int i = l; i < r; i++)
arr[i] = new Integer(1);
}
}
public class Main {
final static int MAX = 10000000;
final static int tnum = 4;
public static void main(String[] args) throws InterruptedException {
int cores = Runtime.getRuntime().availableProcessors();
System.out.println(cores);
Integer[] arr = new Integer[MAX];
Thread[] t = new Thread[tnum];
if(MAX % tnum != 0)
throw new IllegalStateException();
int step = MAX / tnum;
int l = 0, r = 0;
for(int i = 0; i < tnum; i++) {
l = r;
r += step;
t[i] = new Thread(new ArrFill(l, r, arr));
t[i].start();
}
for(int i = 0; i < tnum; i++)
t[i].join();
int res = 0;
for(int i = 0; i < MAX; i++)
if(arr[i] != null)
res += arr[i];
System.out.println(res == MAX);
}
}
I have run this program many times although I never seen a stale value (null). I have 2 cores. Do you have any idea how this program could be improved to actually present the cached value phenomena? Or maybe you have a completly different approach?
Thanks!
I am trying to do a modelling for some algorithms in java, what i am facing now is i need to run the main of the algorithm 10 times but the process takes 120 minutes to finish so i am doing each run on a thread. What i want is to create 10 threads without repeating the same code in each thread so how to make 10 different threads with the same code to excute. any ideas.
package biodavidcorne;
import java.util.Random;
/**
*
* #author hyder
*/
public class BIODavidCorne extends Thread {
public void run(int Runs) {
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
BIODavidCorne test = new BIODavidCorne();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
try {
int Runs = 0;
int[][] Mean10Runs = new int[10][10000];
int[][] Min10Runs = new int[10][10000];
int[][] Max10Runs = new int[10][10000];
// for (int Runs = 0; Runs < 10; Runs++) {
BinList test = new BinList();
Random generator = new Random();
for (int i = 0; i < 10; i++) {
test.ReadLine("File.txt", i);
}
//test.PrintListOfGarbage();
for (int i = 0; i < 10; i++) {
test.InsertGarbageToBin(i);
}
for (int Big = 0; Big < 10000; Big++) {
int Mean = 0;
for (int x = 0; x < 10; x++) {
for (int i = 0; i < 50; i++) {
test.GetPenalties(x, i);
}
}
// System.out.println("*******************************************************************************************" + Big + " .. " + Runs);
// test.PrintListOfGarbage();
int[] penalty = new int[10];
int[] minimum = new int[10];
int[] maximum = new int[10];
int[] mutation = new int[10];
// test.PrintListOfGarbage();
for (int i = 0; i < 10; i++) {
penalty[i] = test.getAllPanalties(i);
}
for (int i = 0; i < 10; i++) {
minimum[i] = test.getMinimum(i);
maximum[i] = test.getMaximum(i);
mutation[i] = test.calculateMutation(penalty[i], minimum[i], maximum[i]);
//
}
int r = generator.nextInt(10);
int s = generator.nextInt(10);
test.MakeTheFitness(mutation, r, s);
test.resetPenaltyArray();
// test.PrintListOfGarbage();
for (int i = 0; i < 10; i++) {
Mean = Mean + mutation[i];
}
int min = mutation[0];
int max = 0;
for (int i = 0; i < 10; i++) {
if (min > mutation[i]) {
min = mutation[i];
}
if (max < mutation[i]) {
max = mutation[i];
}
}
Min10Runs[Runs][Big] = min;
Max10Runs[Runs][Big] = max;
Mean10Runs[Runs][Big] = (Mean / 10);
System.out.println("This is the Mean 1"+Big+".."+Runs);
}
System.out.println("This is the Mean + for Runs" + Runs + ".. " + Mean10Runs[Runs][9999] + "This is the Minimum " + Min10Runs[Runs][9999]);
} catch (Exception e) {
System.out.println("Not supported yet." + e);
}
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
try {
int Runs = 0;
int[][] Mean10Runs = new int[10][10000];
int[][] Min10Runs = new int[10][10000];
int[][] Max10Runs = new int[10][10000];
// for (int Runs = 0; Runs < 10; Runs++) {
BinList test = new BinList();
Random generator = new Random();
for (int i = 0; i < 10; i++) {
test.ReadLine("File.txt", i);
}
//test.PrintListOfGarbage();
for (int i = 0; i < 10; i++) {
test.InsertGarbageToBin(i);
}
for (int Big = 0; Big < 10000; Big++) {
int Mean = 0;
for (int x = 0; x < 10; x++) {
for (int i = 0; i < 50; i++) {
test.GetPenalties(x, i);
}
}
// System.out.println("*******************************************************************************************" + Big + " .. " + Runs);
// test.PrintListOfGarbage();
int[] penalty = new int[10];
int[] minimum = new int[10];
int[] maximum = new int[10];
int[] mutation = new int[10];
// test.PrintListOfGarbage();
for (int i = 0; i < 10; i++) {
penalty[i] = test.getAllPanalties(i);
}
for (int i = 0; i < 10; i++) {
minimum[i] = test.getMinimum(i);
maximum[i] = test.getMaximum(i);
mutation[i] = test.calculateMutation(penalty[i], minimum[i], maximum[i]);
//
}
int r = generator.nextInt(10);
int s = generator.nextInt(10);
test.MakeTheFitness(mutation, r, s);
test.resetPenaltyArray();
// test.PrintListOfGarbage();
for (int i = 0; i < 10; i++) {
Mean = Mean + mutation[i];
}
int min = mutation[0];
int max = 0;
for (int i = 0; i < 10; i++) {
if (min > mutation[i]) {
min = mutation[i];
}
if (max < mutation[i]) {
max = mutation[i];
}
}
Min10Runs[Runs][Big] = min;
Max10Runs[Runs][Big] = max;
Mean10Runs[Runs][Big] = (Mean / 10);
System.out.println("This is the Mean 2"+Big+".."+Runs);
}
} catch (Exception e) {
System.out.println("Not supported yet." + e);
}
}
});
t1.start();
t2.start();
}
}
Just make the Runnable a named class instead of an anonymous inner class, and reuse it:
class MyRunnable implements Runnable {
#Override
public void run() {
int Runs = 0;
int[][] Mean10Runs = new int[10][10000];
// ...
new Thread(new MyRunnable()).start();
You can (and should) put MyRunnable in its own source file.
There is no reason to copy and paste the content of the anonymous inner class ten times. Just assign it to a variable and use it 10 times.
Runnable runnable = new Runnable() {
#Override
public void run() {
// ... the code in the anonymous inner class
}
}
// Start 10 threads with this code
for (int i = 0; i < 10; ++i) {
new Thread(runnable).start();
}
You can use a for loop to create the threads.
Also, if you want to ensure that all of the threads kick off at the same time, you can use a CyclicBarrier, but if not you can just start each thread as you create it.
If you need to hold a reference to the threads, store them in a Thread array
CyclicBarrier barrier = new CyclicBarrrier(10);
// Runnable runnable = ... your code. at the beginning of the Runnable put the first line
barrier.await(); // and catch the exception
Thread[] threads = new Thread[10];
for(int i = 0; i < 10; i++){
threads[i] = new Thread(runnable);
threads[i].start();
}
That's it! Good luck - let me know if you need help implementing the runnable
Unless you have 10 CPU cores do not spawn 10 threads.
You can use commons threadpool and set it the size of the number of cpu cores, so you can run the tasks in parallel and sequentially.
try using a ThreadPoolExecutor
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html
Create a class that extends Thread and implement the run method. You could pass argument through the constructor, keep them as members to use them in the run() method.
Something like this:
public class YourThread extends Thread{
private String mParam1;
private Object mParam2;
public YourThread( String param1, Object param2 ){
mParam1 = param1;
mParam2 = param2;
}
public void run(){
// do your stuff here
// ...
}
}
In the other class:
YourThread t1 = new Thread( "toto", new Object() );
t1.start();
YourThread t2 = new Thread( "titi", new Object() );
t2.start();