Difference between revisions of "Java Threads"
Line 1: | Line 1: | ||
− | + | ===What is the difference between processes and threads ?=== | |
#* A process is an execution of a program, while a Thread is a single execution sequence within a process. A process can contain multiple threads. A Thread is sometimes called a lightweight process. | #* A process is an execution of a program, while a Thread is a single execution sequence within a process. A process can contain multiple threads. A Thread is sometimes called a lightweight process. | ||
− | + | ===Explain different ways of creating a thread.Which one would you prefer and why ?=== | |
#* There are three ways that can be used in order for a Thread to be created: | #* There are three ways that can be used in order for a Thread to be created: | ||
#** A class may extend the Thread class. | #** A class may extend the Thread class. | ||
Line 7: | Line 7: | ||
#* An application can use the Executor framework, in order to create a thread pool. | #* An application can use the Executor framework, in order to create a thread pool. | ||
#* The Runnable interface is preferred, as it does not require an object to inherit the Thread class. In case your application design requires multiple inheritance, only interfaces can help you. Also, the thread pool is very efficient and can be implemented and used very easily. | #* The Runnable interface is preferred, as it does not require an object to inherit the Thread class. In case your application design requires multiple inheritance, only interfaces can help you. Also, the thread pool is very efficient and can be implemented and used very easily. | ||
− | + | === Explain the available thread states in a high-level?=== | |
#* During its execution, a thread can reside in one of the following states: | #* During its execution, a thread can reside in one of the following states: | ||
#** Runnable: A thread becomes ready to run, but does not necessarily start running immediately. | #** Runnable: A thread becomes ready to run, but does not necessarily start running immediately. | ||
Line 16: | Line 16: | ||
#** Blocked on Synchronization: Waiting to acquire a lock. | #** Blocked on Synchronization: Waiting to acquire a lock. | ||
#** Dead: The thread has finished its execution. | #** Dead: The thread has finished its execution. | ||
− | + | === What is the difference between a synchronized method and a synchronized block ?=== | |
#* In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in a method level (coarse grained lock) or block level of code (fine grained lock). | #* In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in a method level (coarse grained lock) or block level of code (fine grained lock). | ||
# How does thread synchronization occurs inside a monitor ? What levels of synchronization can you apply ? | # How does thread synchronization occurs inside a monitor ? What levels of synchronization can you apply ? | ||
#* The JVM uses locks in conjunction with monitors. A monitor is basically a guardian that watches over a sequence of synchronized code and ensuring that only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. The thread is not allowed to execute the code until it obtains the lock. | #* The JVM uses locks in conjunction with monitors. A monitor is basically a guardian that watches over a sequence of synchronized code and ensuring that only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. The thread is not allowed to execute the code until it obtains the lock. | ||
− | + | === What’s a deadlock ?=== | |
#* A condition that occurs when two processes are waiting for each other to complete, before proceeding. The result is that both processes wait endlessly. | #* A condition that occurs when two processes are waiting for each other to complete, before proceeding. The result is that both processes wait endlessly. | ||
# How do you ensure that N threads can access N resources without deadlock ? | # How do you ensure that N threads can access N resources without deadlock ? |
Revision as of 06:02, 9 July 2018
Contents
- 1 What is the difference between processes and threads ?
- 2 Explain different ways of creating a thread.Which one would you prefer and why ?
- 3 Explain the available thread states in a high-level?
- 4 What is the difference between a synchronized method and a synchronized block ?
- 5 What’s a deadlock ?
- 6 Java Examples - Monitoring a Thread
What is the difference between processes and threads ?
- A process is an execution of a program, while a Thread is a single execution sequence within a process. A process can contain multiple threads. A Thread is sometimes called a lightweight process.
Explain different ways of creating a thread.Which one would you prefer and why ?
- There are three ways that can be used in order for a Thread to be created:
- A class may extend the Thread class.
- A class may implement the Runnable interface.
- An application can use the Executor framework, in order to create a thread pool.
- The Runnable interface is preferred, as it does not require an object to inherit the Thread class. In case your application design requires multiple inheritance, only interfaces can help you. Also, the thread pool is very efficient and can be implemented and used very easily.
- There are three ways that can be used in order for a Thread to be created:
Explain the available thread states in a high-level?
- During its execution, a thread can reside in one of the following states:
- Runnable: A thread becomes ready to run, but does not necessarily start running immediately.
- Running: The processor is actively executing the thread code.
- Waiting: A thread is in a blocked state waiting for some external processing to finish.
- Sleeping: The thread is forced to sleep.
- Blocked on I/O: Waiting for an I/O operation to complete.
- Blocked on Synchronization: Waiting to acquire a lock.
- Dead: The thread has finished its execution.
- During its execution, a thread can reside in one of the following states:
What is the difference between a synchronized method and a synchronized block ?
- In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in a method level (coarse grained lock) or block level of code (fine grained lock).
- How does thread synchronization occurs inside a monitor ? What levels of synchronization can you apply ?
- The JVM uses locks in conjunction with monitors. A monitor is basically a guardian that watches over a sequence of synchronized code and ensuring that only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. The thread is not allowed to execute the code until it obtains the lock.
What’s a deadlock ?
- A condition that occurs when two processes are waiting for each other to complete, before proceeding. The result is that both processes wait endlessly.
- How do you ensure that N threads can access N resources without deadlock ?
- A very simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to follow that ordering. Thus, if all threads lock and unlock the mutexes in the same order, no deadlocks can arise.
Java Examples - Monitoring a Thread
How to monitor a thread's status?
Following example demonstrates how to monitor a thread's status by extending Thread class and using currentThread.getName() method.
class MyThread extends Thread {
boolean waiting = true;
boolean ready = false;
MyThread() {
}
public void run() {
String thrdName = Thread.currentThread().getName();
System.out.println(thrdName + " starting.");
while(waiting) System.out.println("waiting:"+waiting);
System.out.println("waiting...");
startWait();
try {
Thread.sleep(1000);
} catch(Exception exc) {
System.out.println(thrdName + " interrupted.");
}
System.out.println(thrdName + " terminating.");
}
synchronized void startWait() {
try {
while(!ready) wait();
} catch(InterruptedException exc) {
System.out.println("wait() interrupted");
}
}
synchronized void notice() {
ready = true;
notify();
}
}
public class new_class {
public static void main(String args[]) throws Exception {
MyThread thrd = new MyThread();
thrd.setName("MyThread #1");
showThreadStatus(thrd);
thrd.start();
Thread.sleep(50);
showThreadStatus(thrd);
thrd.waiting = false;
Thread.sleep(50);
showThreadStatus(thrd);
thrd.notice();
Thread.sleep(50);
showThreadStatus(thrd);
while(thrd.isAlive())
System.out.println("alive");
showThreadStatus(thrd);
}
static void showThreadStatus(Thread thrd) {
System.out.println(thrd.getName()+" Alive:="+thrd.isAlive()+" State:=" + thrd.getState() );
}
}
Result
The above code sample will produce the following result.
main Alive=true State:=running