Java Multi-Threading Flashcards
What is a thread?
The atomic part of program that can run with other similar atomic parts concurrently.
What is the difference between a process and a thread in Java?
A process can be referred as program in execution whereas thread is smallest part of process.
A process has its own address space, different from other processes. Multiple threads share the same address space of the process to which they belong.
As a process can have multiple threads, it is heavy. Thread is lightweight.
Context switching and Inter-thread communication is faster in threads than in processes.
What is multi-threaded programming/multi-threading?
Multi-threading is a programming model that allows multiple threads to exist within the context of one process. These threads can execute concurrently.
What are the benefits of multi-threaded programming?
In multi-threading, multiple threads execute concurrently, which improves the performance.
As multiple threads share the same heap space, it is beneficial to create multiple threads rather than multiple processes.
What is the difference between user thread and daemon thread?
When a user creates a thread in a program, it is called user thread. A daemon thread is a low priority thread that runs in the background to perform tasks such as garbage collection.
JVM will shut down once all the user threads are finished working. Daemon threads do not prevent JVM shutdown. JVM will simply exit even if a daemon thread is working.
Explain daemon thread.
A daemon thread is a low priority thread that runs in the background to perform tasks such as
- garbage collection, created by JVM itself
- polling remote systems for status changes
- sending email notifications etc
- perform scheduled maintenance
JVM will shut down once all the non-deamon threads are finished working. Hence the daemon threads get automatically terminated when all normal threads have been terminated.
If we want to create a daemon thread, we need to call a setDaemon( boolean ) on an existing user thread to make it daemon. Any new thread spawned from a daemon thread will inherit its properties and become daemon thread.
How can we create a thread in Java?
We can create a thread object as:
Thread thread = new Thread( );
To start the thread, we call start( ) method on thread object:
thread.start( );
As this does not specify any code for thread to execute, it will stop right away.
There are two ways to specify what code the thread should execute:
- extending Thread class: and overriding the run( ) method
- passing an object that implements java.lang.Runnable to Thread constructor.
Explain thread creation with Thread subclass.
- Create a class that extends the Thread class
- Override its run( ) method
public class MyThread extends Thread {
public void run(){ System.out.println("MyThread running"); } }
- In the main( ) method, create an object of MyThread and call its start( ) method.
MyThread myThread = new MyThread(); myTread.start();
In Java 8, this can be condensed to:
public static void main( String[ ] args) {
Thread t= new Thread( ) {
@Override public void run( ) { System.out.println("My thread is running"); } };
t.start();
}
Explain thread creation with Runnable implementation.
- Create a class that implements java.lang.Runnable interface
- Override its run( ) method
public class MyRunnable implements Runnable {
public void run(){ System.out.println("MyRunnable running"); } }
- Pass an instance of the MyRunnable class to a Thread constructor and call the start( ) method on thread object.
Runnable runnable = new MyRunnable( );
Thread thread = new Thread ( runnable );
thread.start( );
What happens if we call run( ) method on a thread object instead of start( )?
The thread will execute the given code but the execution will not be performed by a new thread. Rather it will be done by the original thread which created the thread.
Generally, the run( ) method is executed by new thread when start( ) is called.
How can we give a name to a thread?
We can pass the name string to the thread constructor.
With Thread subclassing: Thread thread = new Thread("Thread #1");
With Runnable implementation: MyRunnable runnable = new MyRunnable( ); Thread thread = new Thread(runnable, "New Thread");
And then retrieve it with
thread.getName( );
How can we pause a thread?
A thread can pause itself by calling the static method Thread.sleep() which takes number of milliseconds as parameter.
The sleep() method will attempt to sleep that number of milliseconds before resuming execution.
try { Thread.sleep(10L * 1000L); } catch (InterruptedException e) { e.printStackTrace(); }
Explain a thread’s lifecycle.
java. lang.Thread contains an enum State, which defines its 6 potential states. During any given point of time, the thread can be in only one state.
1. NEW: a newly created thread that has not yet started the execution.
2. RUNNABLE: either running or ready for execution but it’s waiting for resource allocation
3. BLOCKED: waiting to acquire monitor lock to enter/reenter a synchronized block/method
4. WAITING: waiting for some other thread to perform a particular action without any time limit
5. TIMED_WAITING: waiting for some other thread to perform a specific action for a specified period
6. TERMINATED: has completed its execution
Explain the NEW state of thread.
A NEW Thread is a thread that’s been created but not yet started. It remains in this state until we start it using the start( ) method.
Main m= new Main( ); Thread t = new Thread (m); System.out.println( t.getState( ) );
will print NEW.
Explain the RUNNABLE state of thread.
When we create a new thread and call the start() method on that, it moves from NEW to RUNNABLE state. Threads in this state are either running or ready to run, but they’re waiting for resource allocation from the system.
Main m= new Main( ); Thread t = new Thread (m); t.start( ); System.out.println( t.getState( ) );
will print RUNNABLE.
In a multi-threaded environment, the Thread Scheduler allocates a fixed amount of time to each thread. After it has run for a particular amount of time for a thread, it will relinquish the control to other RUNNABLE threads.