Threads are a concept similar to Processes, but with important differences.
To begin this discussion, we examined a quicksort program written in Java. The idea is to have two threads working on separate parts of the data. There are at least two ways to do this with the quicksort program.
We use tactic 1 in the code given below.
import java.util.Random;
public class Main
{
private static int arraySize = 100000;
private static int [] a = new int [arraySize];
private static Random randomIntGenerator = new Random(359);
public static void main(String args[]) throws InterruptedException
{
for (int i = 0; i < a.length; i++)
{
a[i] = randomIntGenerator.nextInt(1000000);
}
int start = (int)System.currentTimeMillis();
QuicksortThreaded qs1 = new QuicksortThreaded(a, 0, (a.length-1)/2);
QuicksortThreaded qs2 = new QuicksortThreaded(a, (a.length-1)/2+1, a.length-1);
Thread qsThread1 = new Thread(qs1);
Thread qsThread2 = new Thread(qs2);
qsThread1.start();
qsThread2.start();
qsThread1.join();
qsThread2.join();
int stop = (int)System.currentTimeMillis();
int elapsedTime = stop - start;
System.out.println("Elapsed time: " + elapsedTime);
// for (int i=0; i < a.length; i++)
// System.out.println(a[i]);
// call method merge here to merge the two sorted halves of the array
}
}
Will the threaded program run faster than a program that does not use threads?
An assignment was given to answer this question.