Skip to content

Week 12: Java – Multithreading


Q1. Candidate Exam Evaluation Using Threads

Objective: Evaluate multiple candidates concurrently using threads.

import java.util.*;

class Candidate extends Thread {
    private String name;
    private String[] candidateAnswers;
    private float totalScore = 0.0f;

    private static final String[] CORRECT_ANSWERS = {"A","B","B","A","C"};

    public Candidate(String name, String[] candidateAnswers){
        this.name = name;
        this.candidateAnswers = candidateAnswers;
    }

    @Override
    public void run() {
        for(int i = 0; i < CORRECT_ANSWERS.length; i++) {
            String correct = CORRECT_ANSWERS[i];
            String candidate = candidateAnswers[i].toUpperCase();

            if (candidate.equals(correct)) {
                totalScore += 2.0f;   // +2 marks for correct
            } else if (!candidate.equals("X")) {
                totalScore -= 0.25f;  // -0.25 for wrong
            }
        }
        System.out.printf("%s scored: %.2f marks\n", name, totalScore);
    }

    public String getCandidateName() { return name; }
    public float getTotalScore() { return totalScore; }
}

public class q1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter number of candidates: ");
        int n = scanner.nextInt();
        scanner.nextLine();

        List<Candidate> candidates = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            System.out.printf("Enter name of candidate %d: ", i + 1);
            String name = scanner.nextLine();

            System.out.println("Enter answers (A/B/C/D/X) for 5 questions separated by spaces: ");
            String[] answersArray = scanner.nextLine().trim().split("\\s+");

            candidates.add(new Candidate(name, answersArray));
        }

        System.out.println("\nEvaluation in progress...");
        for (Candidate candidate : candidates) {
            candidate.start();  // each candidate evaluated in parallel
        }

        for (Candidate candidate : candidates) {
            try {
                candidate.join();  // wait for all threads to finish
            } catch (InterruptedException e) {}
        }

        // Sort candidates by total score (descending)
        candidates.sort(Comparator.comparing(Candidate::getTotalScore).reversed());

        System.out.println("\n--- Rank List ---");
        for (int i = 0; i < candidates.size(); i++) {
            Candidate candidate = candidates.get(i);
            System.out.printf("%d. %s -> %.2f marks\n", i + 1, candidate.getCandidateName(), candidate.getTotalScore());
        }
    }
}

Key Concepts:

  • Thread class is extended to create separate threads for each candidate.
  • start() initiates the thread.
  • join() waits for a thread to finish before proceeding.
  • Multithreading allows parallel evaluation of candidates.
  • Comparator used to sort candidates based on score.

Q2. Simple Thread Printing Example

Objective: Demonstrate two threads running concurrently.

class MorningThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.print("Good Morning ");
            try { Thread.sleep(1000); } catch (InterruptedException e) {}
        }
    }
}

class EveningThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.print("Good Evening ");
            try { Thread.sleep(1000); } catch (InterruptedException e) {}
        }
    }
}

public class q2 {
    public static void main(String[] args) {
        MorningThread m = new MorningThread();
        EveningThread e = new EveningThread();

        m.start();
        e.start();
    }
}

Key Concepts:

  • Two threads (MorningThread and EveningThread) run concurrently.
  • Thread.sleep(1000) pauses a thread for 1 second between prints.
  • Output may interleave, showing real concurrent execution.

Week 12 Concepts Summary

  1. Thread Class

  2. Extend Thread or implement Runnable.

  3. Override run() to define thread task.
  4. Starting a Thread

  5. Use start() (not run()) to begin execution in a new thread.

  6. Thread Synchronization

  7. join() ensures main thread waits for others to finish.

  8. Concurrency

  9. Multiple threads execute simultaneously.

  10. Output can interleave, demonstrating parallelism.
  11. Thread Control

  12. sleep(milliseconds) pauses execution temporarily.


Comments