Threading
The Java language supports concurrent programming from the ground up. This enables running two or more parts of the program concurrently. Each part of such a program is called a thread
. In a Java program, there's at least one thread, the main thread
. The main thread has the ability to create additional threads.
Thread Objects
Thread objects are created from the Thread
class. Threads can be used to run slow running processes asynchronously, such as performing networking operations of complicated Math calculations.
Defining and Starting a Thread
They are two ways to use a thread :
- Extend the Thread class
- Implement the Runnable interface
Extending the Thread Class
This is not recommended due to Java single inheritance. Once the class extends the Thread class it can no longer extend any other class.
The run method should be implemented. Code in the run method will automatically run in a separate thread when the thread object is started.
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
Implement the Runnable Interface
This is the recommend way of using the threads. The class should implement the run method.
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Starting a Thread
For a class that extends the Thread class, we can simply call the start method to start the thread as a separate execution as follows :
HelloThread thread = new HelloThread();
thread.start();
For a class that extends the Runnable interface, we can start the thread by passing it to the Thread class and calling start as follows :
HelloThread thread = new HelloThread();
new Thread(thread).start();
Or we can also use the Runnable interface anonymously as follows :
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Run code here in a separate thread of execution");
}
}).start();
Pausing a Thread
We can pause the execution of a thread by calling the static method sleep and passing in the number of milliseconds to pause. The sleep method throws an exception, so it should be wrapped in a try-catch block.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Interrupting a Thread
We can interrupt a thread by calling the interrupt method. This will signal the thread to stop.