Skip to main content

VNSGU BCA Sem 4: Java Programming (403) Practical Solutions - April 2025 Set F

Paper Details
  • Subject: Java Programming Language
  • Subject Code: 403
  • Set: F
  • Semester: 4
  • Month/Year: April 2025
  • Max Marks: 25
  • Time Recommendation: 45 Minutes
  • Paper: View Paper | Download PDF

Questions & Solutions

All questions are compulsory

Q1: Thread Implementation

Max Marks: 20

Write a Java program to create a thread that prints "Hello from Thread" five times using the Thread class.

1. Understanding Threads

Learn the basics of multithreading in Java.

Hint
  • Thread: A separate flow of execution within a program
  • Two ways to create threads:
    1. Extend Thread class and override run() method
    2. Implement Runnable interface and pass to Thread constructor
  • start(): Begins thread execution, calls run() internally

2. Method 1: Extending Thread Class

Create a thread by extending the Thread class.

Hint

Extend Thread class, override run() method with your code, create object and call start().

View Solution - Extending Thread
// Create thread by extending Thread class
class MyThread extends Thread {
@Override
public void run() {
// Code to be executed by the thread
for (int i = 1; i <= 5; i++) {
System.out.println("Hello from Thread - Count: " + i);

// Optional: Add small delay to see thread execution
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
}
}

// Main class
public class ThreadDemo {
public static void main(String[] args) {
System.out.println("Main thread starting...\n");

// Create thread object
MyThread myThread = new MyThread();

// Start the thread (calls run() internally)
myThread.start();

// Main thread continues execution
System.out.println("Main thread continuing...");
System.out.println("Waiting for MyThread to complete...\n");

// Wait for thread to complete (optional)
try {
myThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("\nMain thread ending.");
}
}

Output:

Main thread starting...

Main thread continuing...
Waiting for MyThread to complete...

Hello from Thread - Count: 1
Hello from Thread - Count: 2
Hello from Thread - Count: 3
Hello from Thread - Count: 4
Hello from Thread - Count: 5

Main thread ending.

Step-by-Step Explanation:

  1. Initialization: Create MyThread class extending Thread
  2. Logic Flow:
    • Override run() method with loop printing message 5 times
    • Create thread object in main
    • Call start() to begin thread execution
    • join() waits for thread to complete
  3. Completion: Thread prints message 5 times independently

3. Method 2: Implementing Runnable Interface

Alternative approach using Runnable interface.

Hint

Implement Runnable, implement run() method, create Thread object passing Runnable.

View Solution - Implementing Runnable
// Create thread by implementing Runnable interface
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Hello from Runnable Thread - Count: " + i);

try {
Thread.sleep(300); // 300ms delay
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage());
}
}
}
}

public class RunnableDemo {
public static void main(String[] args) {
System.out.println("Creating thread using Runnable...\n");

// Create Runnable object
MyRunnable myRunnable = new MyRunnable();

// Create Thread object with Runnable
Thread thread = new Thread(myRunnable);

// Set thread name (optional)
thread.setName("MyWorkerThread");

// Start the thread
thread.start();

// Main thread work
for (int i = 1; i <= 3; i++) {
System.out.println("Main thread working: " + i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

// Wait for worker thread
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("\nBoth threads completed.");
}
}

Output:

Creating thread using Runnable...

Main thread working: 1
Hello from Runnable Thread - Count: 1
Main thread working: 2
Hello from Runnable Thread - Count: 2
Hello from Runnable Thread - Count: 3
Main thread working: 3
Hello from Runnable Thread - Count: 4
Hello from Runnable Thread - Count: 5

Both threads completed.

Step-by-Step Explanation:

  1. Initialization: Create MyRunnable implementing Runnable
  2. Logic Flow:
    • Implement run() method with task logic
    • Create Runnable instance
    • Pass to Thread constructor
    • Both threads run concurrently
  3. Completion: Demonstrates concurrent execution

4. Thread Methods and Properties

Learn useful thread methods.

Common Thread Methods
  • getName() / setName(): Get or set thread name
  • getId(): Get unique thread identifier
  • isAlive(): Check if thread is running
  • sleep(milliseconds): Pause thread execution
  • yield(): Hint to scheduler to run other threads
Thread Information Example
class InfoThread extends Thread {
public InfoThread(String name) {
super(name); // Set thread name via constructor
}

@Override
public void run() {
System.out.println("Thread Name: " + getName());
System.out.println("Thread ID: " + getId());
System.out.println("Priority: " + getPriority());
System.out.println("State: " + getState());

for (int i = 1; i <= 5; i++) {
System.out.println(getName() + ": Hello from Thread " + i);
}
}
}

public class ThreadInfo {
public static void main(String[] args) {
InfoThread thread = new InfoThread("WorkerThread");
System.out.println("Before start - State: " + thread.getState());
thread.start();
System.out.println("After start - State: " + thread.getState());
}
}
Concept Deep Dive: Thread Lifecycle

Thread States:

  • NEW: Thread created but not started
  • RUNNABLE: Ready or running
  • BLOCKED: Waiting for monitor lock
  • WAITING: Waiting indefinitely
  • TIMED_WAITING: Waiting for specified time
  • TERMINATED: Execution completed

Why use Runnable over extending Thread?

  • Java doesn't support multiple inheritance - implementing Runnable keeps class free to extend other classes
  • Better separation of task (Runnable) from execution mechanism (Thread)
  • Same Runnable can be passed to multiple Threads

Q2: Viva Preparation

Max Marks: 5

Potential Viva Questions
  1. Q: What is a thread in Java?

    • A: A thread is a lightweight subprocess, the smallest unit of processing. It enables concurrent execution of code.
  2. Q: What is the difference between start() and run()?

    • A: start() creates a new thread and calls run() internally. Directly calling run() executes in current thread without creating new thread.
  3. Q: What are the two ways to create a thread?

    • A: (1) Extend Thread class and override run(), (2) Implement Runnable interface and pass to Thread constructor.
  4. Q: What is the purpose of Thread.sleep()?

    • A: It pauses the current thread for specified milliseconds. Useful for simulation and preventing CPU overuse.
  5. Q: What is thread priority?

    • A: Hint to scheduler about thread importance. Range 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), default is 5 (NORM_PRIORITY).
  6. Q: What does join() method do?

    • A: Makes the calling thread wait until the joined thread completes execution.
  7. Q: What is multithreading?

    • A: Executing multiple threads simultaneously for better CPU utilization and responsive applications.
Common Pitfalls
  • Calling run() directly: Always call start(), not run(), to create new thread
  • Not handling InterruptedException: Required when using sleep() or join()
  • Race conditions: Multiple threads accessing shared data need synchronization
  • Resource leaks: Always properly stop threads to avoid memory leaks
  • Thread safety: StringBuilder is not thread-safe; use StringBuffer for multi-threaded code

Quick Navigation

SetLink
Set ASolutions
Set BSolutions
Set CSolutions
Set DSolutions
Set ESolutions
Set FCurrent Page

Last Updated: April 2026