Q69. What is a thread?
A thread is a lightweight unit of execution within a process. Multiple threads can execute concurrently.
Q70. How can you create a thread in Java?
Two common approaches:
Extend the Thread class.
Implement the Runnable interface.
class MyTask implements Runnable {
public void run() {
System.out.println("Thread running");
}
}
class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyTask());
t.start();
}
}Q71. Difference between start() and run()?
start()starts a new thread and eventually invokesrun()on that thread.run()called directly executes like an ordinary method on the current thread.
Q72. What is synchronization?
Synchronization controls access to shared resources so that multiple threads do not cause inconsistent results.
synchronized void increment() {
count++;
}Q73. What is a deadlock?
A deadlock occurs when two or more threads wait indefinitely for resources held by one another.
Q74. What is the difference between process and thread?
Process | Thread |
|---|---|
Independent executing program | Execution unit within a process |
Has its own memory space | Shares process memory |
More resource-intensive | Usually lighter |
Communication can be more expensive | Shared-memory communication is easier |
Q75. What is the volatile keyword?
It ensures visibility of changes to a variable across threads. It does not make compound operations like count++ atomic.
Q76. What is the difference between sleep() and wait()?
sleep() | wait() |
|---|---|
Defined in Thread | Defined in Object |
Does not release held monitors | Releases the monitor while waiting |
Used for timed pauses | Used for inter-thread coordination |
Does not require synchronized context | Must own the object's monitor |
Q77. What are the thread lifecycle states?
NEW
RUNNABLE
BLOCKED
WAITING
TIMED_WAITING
TERMINATED