Multithreading basics (concept)

Computer Science · Java

Question 1 of 10

0

    In Java, a thread that has finished running is in the state:

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Multithreading basics (concept) explained

    A thread is an independent path of execution within a program. Multithreading lets a program do several things at once.

    Calling start() on a thread runs it in parallel with the others. Calling run() directly only runs the code on the current thread, which is a common mistake. Threads share objects, so unsynchronised updates to one field can interleave and give a wrong result, a race condition. The synchronized keyword lets only one thread at a time run a method on a given object. join() waits for a thread to finish and can throw InterruptedException, which must be handled.

    class Counter {
        int count = 0;
    
        synchronized void increment() {
            count++;
        }
    }
    
    Counter c = new Counter();
    Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) c.increment(); });
    Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) c.increment(); });
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    System.out.println(c.count);
    

    Worked example

    Trace the program above.

    1. t1 and t2 each call increment 1000 times, so the expected total is 1000+1000=20001000 + 1000 = 2000.
    2. synchronized means only one thread at a time can run increment on c, so no update is lost.
    3. join waits until both threads finish, so main prints after all the updates.
    4. The output is 2000. Without synchronized, two threads could read the same value and lose an update, so the result could be less than 2000.

    What you will practise

    100 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • A thread is:
    • Multithreading lets a program:
    • The Runnable interface:
    • Thread safety:
    • A race condition occurs when:
    • Which method starts a new thread running in Java?
    • Calling run() directly on a Thread object instead of start() will:
    • Which keyword ensures that only one thread at a time runs a method or block for the same lock object?

    …and 92 more.