Practicle Java Sem 1 - Vikalp Sharma
Practicle Java Sem 1 - Vikalp Sharma
AIM: Demonstrate the concept of threads to achieve multitasking program using thread
class and runnable interface separately for below scenario
Steps/Algorithm/Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("\t\t Code for Threads \n\n\n");
System.out.print("Enter the number of elements: ");
int size = scanner.nextInt();
int[] numbers = new int[size];
System.out.println("Enter the elements:");
for (int i = 0; i < size; i++) {
numbers[i] = scanner.nextInt();
}
SummationThread thread1 = new SummationThread("Thread 1", numbers, 0, size / 3 -
1);
SummationThread thread2 = new SummationThread("Thread 2", numbers, size / 3, 2 *
size / 3 - 1);
SummationThread thread3 = new SummationThread("Thread 3", numbers, 2 * size / 3,
size - 1);
thread1.start();
thread2.start();
thread3.start();
try {
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
scanner.close();
}
}
class SummationThread extends Thread {
private int[] numbers;
private int startIndex;
private int endIndex;
private int sum;
public SummationThread(String name, int[] numbers, int startIndex, int endIndex) {
super(name);
this.numbers = numbers;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.sum = 0;
}
public int getSum() {
return sum;
}
@Override
public void run() {
for (int i = startIndex; i <= endIndex; i++) {
sum += numbers[i];
}
System.out.println(getName() + " sum: " + sum);
}
}