Java Multithreading
Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the same time and parallel). It allows a process to run its tasks in parallel mode on a single processor system
Creating a Thread
In Java, there are two ways to create a thread
- Implements the Runnable.jave interface.
- Instantiating a subclass that inherits Thread.java
Using Runnable Interface
Ads by Google


Example:

public class MyRunnable implements Runnable {

/**
* As in the previous example this method is executed
* when the start() method is called on the thread
* so here you will put the 'thread code'.
*/
public void run() {
System.out.println("Thread executed!");
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

//create a Thread object and pass it an object of type Runnable
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}

Output
Thread executed!
By extending Thread:
Example:

public class MyThread extends Thread {

/**
* This method is executed when the start() method is called on the thread
* so here you will put the 'thread code'.
*/
public void run() {
System.out.println("Thread executed!");
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Thread thread = new MyThread();
thread.start();
}
}

Output
Thread executed!

Two Threads Test
The first method in the SimpleThread class is a constructor that takes a String as its only argument. This constructor is implemented by calling a superclass constructor and is interesting to us only because it sets the Thread's name, which is used in the program. The next method in the SimpleThread class is the run() method. The run() method is the heart of any Thread and where the action of the Thread takes place. The run() method of the SimpleThread class contains a for loop that iterates ten times. In each iteration the method displays the iteration number and the name of the Thread, then sleeps for a random interval of up to 1 second. After the loop has finished, the run() method prints "DONE!" along with the name of the thread. That's it for the SimpleThread class.
The TwoThreadsTest class provides a main() method that creates two SimpleThread threads: one is named "Work" and the other is named "Holiday".
The main() method also starts each thread immediately following its construction by calling the start() method.
Example:

public class TwoThreadsTest {
public static void main (String[] args) {
new SimpleThread("Work").start();
new SimpleThread("Holiday").start();
}
}

class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}

Output
0 Work
0 Holiday
1 Holiday
1 Work
2 Work
2 Holiday
3 Work
4 Work
3 Holiday
4 Holiday
5 Holiday
5 Work
6 Work
7 Work
6 Holiday
8 Work
7 Holiday
9 Work
DONE! Work
8 Holiday
9 Holiday
DONE! Holiday
Notice how the output from each thread is intermingled with the output from the other. This is because both SimpleThread threads are running concurrently. Thus, both run() methods are running at the same time and each thread is displaying its output at the same time as the other.
Life cycle of a thread
A thread can be only in one of five states
- New
- Runnable
- Running
- Waiting/Blocked
- Dead

javac
New - This is the state the thread is in after the Thread instance has been created, but the start() method has not been invoked on the thread.The thread is just created still its not running. At this point, the thread is considered not alive. When we create a thread it will be in Newborn State.
Runnable - A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also.. When the thread is in the runnable state, it is considered alive.
Running - This is the state a thread is in when the thread scheduler selects it (from the runnable pool) to be the currently executing process. A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.
Waiting/Blocked - A thread is called in Blocked State when it is not allowed to entering in Runnable State or Running State. It happens when thread is in waiting mode, suspended or in sleeping mode.
Dead - A thread is considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
Previous - Java Exceptions                                                 Next - Java Interview Questions