Last active
May 13, 2021 14:55
-
-
Save anubhavbagri/cd620141fc05de4ff3f794372504f5d4 to your computer and use it in GitHub Desktop.
A multithreaded java program where 4 threads are used to execute parallel search on large number of integers read from a text file and reduce the overall search time.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.io.IOException; | |
import java.nio.file.*; | |
import java.text.DecimalFormat; | |
import java.text.NumberFormat; | |
public class ParallelSearch implements Runnable { | |
private int startIndex, endIndex; | |
private static int nElements, key; | |
public static List<Integer> array = new ArrayList<>(); | |
private boolean flag; // default value is false | |
private String threadName; | |
public static Scanner sc = new Scanner(System.in); | |
public ParallelSearch(int startIndex, int endIndex, String threadName) { | |
this.startIndex = startIndex; | |
this.endIndex = endIndex; | |
this.threadName = threadName; | |
Thread thread = new Thread(this); | |
thread.start(); | |
} | |
@Override | |
public void run() { | |
for (int i = startIndex; i <= endIndex; i++) { | |
if (key == array.get(i)) { | |
// System.out.println("\nSearch is successful by " + threadName + " and " + key + " found at position " + i); | |
System.out.print("\nSearch is successful by " + threadName); | |
flag = true; | |
return; | |
} | |
} | |
if (flag == false) { | |
System.out.print("\nSearch is unsuccessful by " + threadName); | |
} | |
} | |
public static void main(String[] args) throws IOException { | |
long start = System.currentTimeMillis(); | |
Path filePath = Paths.get("file.txt"); | |
Scanner scanner = new Scanner(filePath); | |
// List<Integer> array = new ArrayList<>(); | |
while (scanner.hasNext()) { | |
if (scanner.hasNextInt()) { | |
array.add(scanner.nextInt()); | |
} else { | |
scanner.next(); | |
} | |
} | |
nElements = array.size(); | |
System.out.print("\nEnter the value to be searched : "); | |
key = sc.nextInt(); | |
// creating anonymous object | |
new ParallelSearch(0, (nElements / 4) - 1, "Thread 1"); | |
new ParallelSearch(nElements / 4, (nElements / 2) - 1, "Thread 2"); | |
new ParallelSearch(nElements / 2, ((3 * nElements) / 4 - 1), "Thread 3"); | |
new ParallelSearch((3 * nElements) / 4, nElements - 1, "Thread 4"); | |
// worst case scenario - last thread tak baat chali jayegi | |
scanner.close(); | |
long end = System.currentTimeMillis(); | |
NumberFormat formatter = new DecimalFormat("#0.00000"); | |
System.out.println("\n\nExecution time is " + formatter.format((end - start) / 1000d) + " seconds"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment