PRACTICAL EXAM-ANSWER SHEET
Enrollment Number : EC2332251010282 Name of student : VIKALP SHARMA Date :
11-07-2023 Subject Code : V20PCA101
Name of Subject: Programming using Java
AIM: Demonstrate the concept of threads to achieve multitasking program using thread
class and runnable interface separately for below scenario
Create an Array of 9 threads and create three
threads and each threads has to add up and report the
answer to the main thread where the main thread waits for the three threads and
computes the summation of all the three threads Note: assign names of the threads
as well.
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();
}
int totalSum = thread1.getSum() + thread2.getSum() + thread3.getSum();
System.out.println("Total sum: " + totalSum);
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);
}
}
Output: compiler online