Multithreading
- Parallel Programming
- To take full advantage of CPU power.
- For reducing response time
- To sever multiple clients at the same time.
- User Thread/high-priority thread -> The JVM will wait for any user thread to complete its task before terminating it.
- Daemon Thread/low-priority thread-> daemon threads are low-priority threads whose only role is to provide services to user threads.
- Example: main method, garbage collector
- By extending the Thread Class
- By implementing the Runnable interface
public class Thread extends Object implements Runnable
Signature of Runnable interface
public interface Runnable
When we should use Runnable interface or Thread class?
We should use runnable interface when we are only planning to override the run() method and because this interface contains only run() method not others.
If we want to use the multiple methods which are present in Thread calss then we should go for Thread Class.
By extending the Thread Class
class MyThread extends Thread{
public void run()
{
System.out.println("concurrent thread started running..");
}
}
classMyThreadDemo{
public static void main(String args[])
{
MyThread mt = new MyThread();
mt.start();
}
}
start() method: On calling start(), a new stack is provided to the thread and run() method is called to introduce the new thread into the program. Read More
Some Important points to Remember when we extens Thread class.
- When we extend Thread class, we cannot override setName() and getName() functions, because they are declared final in Thread class.
- While using sleep(), always handle the exception it throws.
static void sleep(long milliseconds) throws InterruptedException
Some useful public static methods are:
- public static native Thread currentThread();
- public static native void yield();
- public static native void sleep(long millis) throws InterruptedException
- public static void sleep(long millis, int nanos) throws InterruptedException
- public static boolean interrupted()
- Each thread starts in a separate call stack.
- Invoking the run() method from the main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.