Multithreading

In parallel programming models, Java can run multithreaded programs on both single and multiple JVM models. In a single JVM, multithreading can be achieved by the Java native threads or another shared memory pattern, such as OpenMP. When you have multiple JVMs, individual programs execute in the respective JVM, and they can communicate using Java APIs such as RMI or MPJ, as shown in the following diagram:

The Java thread class java.lang.Thread can produce instances of Thread to be able to run, spawn, and fork/join multiple threads, as shown in the following example that consists of five threads:

package threads;

public class SpawningThreads {

public static void main(String args[]){
int threadCount = 5;
Thread threadGroup [] = new Thread[threadCount];
for(int iter1=0; iter1<threadCount; iter1++){
threadGroup[iter1] = new Thread(new RunnableComponent(iter1));
threadGroup[iter1].start();
}
for(int iter2=0; iter2<threadCount; iter2++){
try{
threadGroup[iter2].join();
}catch (InterruptedException x){}
}
System.out.println("From the Master Thread Execution");
}
}
class RunnableComponent implements Runnable {
int iter3;
public RunnableComponent(int j) {
this.iter3 = j;
}
public void run() {
System.out.println("From the Spawned Thread Execution");
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset