1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 5

CAP477 · Unit 5: Concurrency and I/O

Threads and Runnable

8 practice questions

Key points

  • start() creates a thread, run() does not
  • A thread can be started once
  • States: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
  • Callable returns a value via Future; Runnable does not

A thread is an independent path of execution inside a process. Java creates threads two ways:

  1. class W extends Thread { public void run() {...} }
  2. Implement `Runnable` (preferred; lets the class extend something else) and pass it to new Thread(runnable); lambdas work: new Thread(() -> ...).

start() vs run(): start() creates a new thread that then calls run(). Calling run() directly just executes the method on the current thread (it printed in main, not in worker). A thread can be started only once: a second start() throws IllegalThreadStateException.

States: NEW -> RUNNABLE -> (BLOCKED waiting for a monitor | WAITING | TIMED_WAITING e.g. sleep(300)) -> TERMINATED. join() makes the caller wait for another thread to finish.

Other facts: priorities range from MIN_PRIORITY 1 through NORM_PRIORITY 5 to MAX_PRIORITY 10 (only hints). A daemon thread (setDaemon(true) before start) does not keep the JVM alive; main is not a daemon. interrupt() on a sleeping thread makes sleep throw InterruptedException and clears the interrupt flag. An uncaught exception ends only that thread (a handler set with setUncaughtExceptionHandler can report it) and main continues.

Executor framework: ExecutorService ex = Executors.newFixedThreadPool(2); reuses pooled threads. submit(Callable) returns a Future whose get() blocks for the result; a Callable<V> returns a value and may throw checked exceptions, while Runnable returns nothing. Always shutdown() the pool.

Exam pitfall: calling run() instead of start() gives no concurrency.

Try two questions

Question 1 · Tier 1, Recall

Which method must you call to run a thread's code concurrently?

  1. start()
  2. launch()
  3. run()
  4. execute()
Show the answer

A. run() executes in the caller: the test printed 'in main' for run() and 'in worker' for start().

Question 2 · Tier 2, Understand

What does thread.join() do when called from main?

  1. Kills the thread
  2. Makes main wait until that thread finishes
  3. Starts the thread
  4. Merges the two threads' stacks
Show the answer

B. The caller blocks until the target thread terminates.