8 Multithreading And Concurrency

Advanced Java Programming ยท Unit 8

Multithreading and Concurrency

Exam-focused notes for Multithreading and Concurrency (Advanced Java Programming, BIT401): what the TU syllabus asks and how it has actually been tested, with 1 solved past questions from this unit.

Multithreading and Concurrency in short

Multithreading lets a program do several tasks at the same time. It keeps a program responsive and makes good use of the processor.

Multithreading and Concurrency: notes

Thread class and Runnable interface

A thread is a small unit of execution inside a program. A process can hold many threads, and they share memory. Java gives two ways to create one.

  • Extend the Thread class and override run().
  • Implement the Runnable interface, write run(), and pass the object to a Thread.

Runnable is usually better because a class can still extend another class. You always start a thread with start(). It creates a new thread that calls run(). Calling run() directly just runs the code in the current thread. Starting the same thread twice throws IllegalThreadStateException.

public class RunnableDemo implements Runnable {
    public void run() {
        System.out.println("Running in " + Thread.currentThread().getName());
    }
    public static void main(String[] args) {
        Thread t = new Thread(new RunnableDemo(), "worker");
        t.start();
    }
}

What this unit covers

  • Thread class and Runnable interface
  • Creating multiple threads
  • Thread lifecycle and states
  • Thread synchronization basics

Thread class and Runnable interface

2080 ยท 5 marks

Write a Java program to create a multi-threaded programs by extending Thread class. Create at least three threads. [5]

Show solved answer

Model Answer: Multi-threaded Program by Extending Thread Class

Program Code

// Define a custom thread class by extending Thread
class MyThread extends Thread {
    private String threadName;
    
    // Constructor
    public MyThread(String name) {
        this.threadName = name;
    }
    
    // Override run() method
    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(threadName + " is running - Count: " + i);
            try {
                // Sleep for 1 second
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
        System.out.println(threadName + " has finished execution");
    }
}

// Main class to create and start threads
public class MultiThreadedProgram {
    public static void main(String[] args) {
        // Create three thread objects
        MyThread thread1 = new MyThread("Thread-1");
        MyThread thread2 = new MyThread("Thread-2");
        MyThread thread3 = new MyThread("Thread-3");
        
        // Start all three threads
        thread1.start();
        thread2.start();
        thread3.start();
        
        System.out.println("Main thread continues...");
    }
}

Output (Sample)

Main thread continues...
Thread-1 is running - Count: 1
Thread-2 is running - Count: 1
Thread-3 is running - Count: 1
Thread-1 is running - Count: 2
Thread-2 is running - Count: 2
Thread-3 is running - Count: 2
...
Thread-1 has finished execution
Thread-2 has finished execution
Thread-3 has finished execution

Key Points Explained

  1. Extend Thread Class: MyThread extends the Thread class
  2. Override run() Method: Contains the code to be executed by the thread
  3. Create Thread Objects: Three separate instances (thread1, thread2, thread3) are created
  4. Call start() Method: Invokes the thread's execution; never call run() directly
  5. Concurrent Execution: All three threads run concurrently, producing interleaved output
  6. Thread.sleep(): Pauses thread execution for specified milliseconds
Open this answer on its own page โ†’