Thread Creation
A thread in Java is represented by an object of the Thread class. Creating threads is achieved in one of two ways:-
- by extending the java.lang.Thread class
- by implementing the java.lang.Runnable interface
Thread class and run() Method:
Basic support for threads is in the java.lang.Thread class. It provides a thread API and all the generic behavior for threads. These behaviors include starting, sleeping, running, yielding, and having a priority.
The run() method gives a thread something to do. Its code should implement the thread’s running behavior. There are two ways of creating a customized thread:
- Sub classing the java.lang.Thread class and Overriding the run() method.
- Implementing the java.lang.Runnable interface and Overriding the run() method.
1. Creating a Thread with the “java.lang.Thread” class
In this technique, a class is declared to be a subclass of Thread. This subclass should override the run() method of class Thread, and we can then allocate and start an instance of that class. For example, here we define the class MyThread to be a subclass of Thread class that starts when we create an instance of it:
class MyThread extends Thread {
MyThread() {
// do standard constructor initialization
start();
}
public void run() {
// Write the code for this thread to be done
}
}
We then create and start a thread of this type, like this:
MyThread thread1 = new MyThread();
2. Creating a Thread with the “java.lang.Runnable” interface
The other way to create a thread class is to declare a class that implements the Runnable interface. The class then implements the run() method. Since there is no start() method in the Runnable interface [it’s only method is run()], we have to create a thread object by passing a runnable target (this) to the constructor of Thread class. Here’s how this looks in code snippet:
class MyRunnable implements Runnable {
Thread thread;
MyRunnable() {
// do standard constructor initialization
thread = new Thread(this, “Runnable Thread”);
thread.start();
}
public void run() {
// Write the code for this thread to be done
}
}
We then create and start a thread of this type, like this:
MyRunnable thread1 = new MyRunnable();
Thread Scheduling
- When we say that threads are running concurrently, in practice it may not be so. On a computer with single CPU, threads actually run one at a time giving an illusion of concurrency.
- The execution of multiple threads on a single CPU based on some algorithm is called thread scheduling.
- Thread scheduler maintains a pool of all the runnable (ready-to-run) threads. Based on fixed priority algorithm, it allocates free CPU to one of these threads.
Summary
Creating threads is achieved in one of the two ways:- ♦ by extending the java.lang.Thread class ♦ by implementing the java.lang.Runnable interface |