Sie sind auf Seite 1von 5

Lab Assignment 3

Java

Name Shashank Keshav


Reg. No. 18BCE0129
Faculty Prof. Kauser Ahmed
Slot L1+L2

1|P ag e
Five events E1, E2, E3, E4 and E5 are going to be organized for Gravitas in VIT,
registration is open for all B.Tech students. With the total strength of 500 students,
simulate the registration for each event by generating 500 random numbers in the
range of 1 – 5. (1 for event E1, 2 for E2… 5 for E5) and store the values in an
array. Create six threads to equally share the task of counting the number of
registration details for all the events. Use synchronized method or synchronized
block to update the count variables. The main thread should receive the final
registration count for all events and display the list of students who have not
registered in any event.

import java.util.*;

import java.io.*;

class CountVote extends Thread {

Vector vec;

int k, i;

public int count = 0;

public CountVote(int k, Vector vec) {

this.k = k;

this.vec = vec;

public synchronized void run() {

try {

for (i = 0; i < vec.size(); i++) {

if (vec.elementAt(i).equals(k)) {

System.out.println("E" + k + " got a count.");

count++;

} catch (Exception e) {

System.out.println(e);

2|P ag e
}

public class H {

public static void main(String[] args) {

Vector votevec = new Vector(503);

Random rand = new Random();

while (votevec.size() < 500) {

int rand_int1 = rand.nextInt(6);

votevec.add(rand_int1);

CountVote ac = new CountVote(1, votevec);

CountVote bc = new CountVote(2, votevec);

CountVote cc = new CountVote(3, votevec);

CountVote dc = new CountVote(4, votevec);

CountVote ec = new CountVote(5, votevec);

ac.start();

bc.start();

cc.start();

dc.start();

ec.start();

try {

ac.join();

bc.join();

cc.join();

dc.join();

3|P ag e
ec.join();

System.out.println("Counting has ended!");

} catch (Exception e) {System.out.println(e);}

int av = ac.count;

int bv = bc.count;

int cv = cc.count;

int dv = cc.count;

int ev = cc.count;

System.out.println(av + " Registrations for E1");

System.out.println(bv + " Registrations for E2");

System.out.println(cv + " Registrations for E3");

System.out.println(dv + " Registrations for E4");

System.out.println(ev + " Registrations for E5");

int cnt = 0;

for (int i = 0; i < 500; i++) {

if (votevec.elementAt(i).equals(0)) {

cnt++;

System.out.println(bv + " Students have not registered in any event");

4|P ag e
Output Screenshot :-

5|P ag e

Das könnte Ihnen auch gefallen