SCJP Java Threads and Concurrency 1 — Questions and Answers
Question 1: Which of the following is a correct way to create a new thread in Java?
- Extend Thread class or implement Runnable interface (Correct answer)
- Implement Callable interface only
- Extend Runnable class
- Use the Process class
Correct answer: Extend Thread class or implement Runnable interface
In Java, threads can be created by extending `Thread` or implementing `Runnable` and passing it to a `Thread` constructor.
Question 2: What does the `synchronized` keyword ensure in Java?
- That a method runs faster
- That only one thread executes the synchronized block/method at a time (Correct answer)
- That threads run in a fixed sequence
- That variables are stored in CPU cache
Correct answer: That only one thread executes the synchronized block/method at a time
`synchronized` acquires a monitor lock on an object, ensuring mutual exclusion so only one thread can execute the guarded code at a time.
Question 3: What is a deadlock in Java threading?
- A thread that runs indefinitely
- Two or more threads permanently blocked waiting for each other's locks (Correct answer)
- A thread that throws an exception
- A thread that uses too much memory
Correct answer: Two or more threads permanently blocked waiting for each other's locks
Deadlock occurs when two or more threads each hold a lock the other needs, causing them to wait indefinitely.
Question 4: What is the difference between `Thread.sleep()` and `Object.wait()` in Java?
- sleep() releases the lock; wait() holds it
- wait() releases the object's lock; sleep() does not release any lock (Correct answer)
- They are identical
- sleep() is for threads; wait() is for processes
Correct answer: wait() releases the object's lock; sleep() does not release any lock
`wait()` releases the object's monitor lock and suspends the thread until notified, while `sleep()` pauses the thread without releasing any locks.
Question 5: Which thread state indicates that a thread is eligible to run but waiting for CPU time?
- BLOCKED
- WAITING
- RUNNABLE (Correct answer)
- NEW
Correct answer: RUNNABLE
A thread in the `RUNNABLE` state is ready to execute and waiting for the CPU scheduler to assign it processor time.
Question 6: What method must be overridden when implementing the `Runnable` interface?
- start()
- execute()
- run() (Correct answer)
- launch()
Correct answer: run()
The `Runnable` interface has a single abstract method `run()`, which contains the code the thread will execute.
Which of the following is a correct way to create a new thread in Java?