Java is a multi-threaded encoding language, which denotes we could expand the multi-threaded agenda with Java. A multi-threaded list encloses two or more divisions that can sprint alongside and each division can switch an unlike task at the identical time making best employ of the accessible resources especially when your computer has numerous CPUs.
By meaning, multitasking is when numerous procedures share ordinary processing reserves such as a CPU. Multi-threading expands the design of multitasking into requests where you could subdivide precise operations inside a solitary application into person threads. Every one of the strands can lope in parallel. The OS partitions dispensation time not only among diverse applications but also amid each thread inside an application.
Multi-threading enabled users to inscribe codes in a way where numerous activities can continue concurrently in an identical program.
A thread goes during various periods in its existence cycle. For instance, a strand is born, begun, runs, and then dies. The subsequent diagram illustrates the whole life cycle of a thread.
Subsequent are the periods of the life cycle:
Each Java thread has precedence that aids the operating system settle on the order in which strands are timetable.
Java thread priorities are in the variety flanked by MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with senior main concerns are more significant to a plan and should be assigned processor time prior to lower-priority threads. However, thread priorities never pledge the organization in which threads affect and are exceedingly much stage-dependent.
If your set is intended for execution as a thread then you could accomplish by realizing a Runnable line. You will necessitate following three essential steps −
Step 1
As a first pace, you require to apply a run() technique offered by a Runnable line. This way offers an entry point for the line and you will set your absolute business reason inside this process. Subsequent is a simple syntax of the run() method:
public void run( )
Step 2
As a subsequent step, you will instantiate a Thread thing using the subsequent constructor:
Thread(Runnable threadObj, String threadName);
Where threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.
Step 3
Once a Thread object is developed, you can create it by calling start() method, which executes a call to run( ) method. Subsequent is a straightforward syntax of start() method
void start();
Example
Here is an example that creates a new thread and starts running it:
class RunnableDemo implements Runnable { private Thread t; private String threadName; RunnableDemo( String name) { threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start(); RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start(); } }
This will produce the following result:
Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting.
The following means to generate a thread is to develop a new class that expands the Thread class with the subsequent two uncomplicated steps. This draw near presents more elasticity in managing multiple threads generated using accessible techniques in Thread class.
Step 1
You will require to dominate the run( ) method accessible in Thread class. This method offers an entry point for the strand and you will set your absolute business reason inside this technique. Subsequent is an uncomplicated syntax of the run() method:
public void run( )
Step 2
Once the Thread object is developed, you can establish it by calling the start () technique, which implements a call to run( ) method. Subsequent is a simple syntax of start() method −
void start( );
Here is the preceding program rewritten to extend the Thread:
class ThreadDemo extends Thread { private Thread t; private String threadName; ThreadDemo( String name) { threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { ThreadDemo T1 = new ThreadDemo( "Thread-1"); T1.start(); ThreadDemo T2 = new ThreadDemo( "Thread-2"); T2.start(); } }
This will produce the following result:
Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting.
Following is the list of important methods available in the Thread class.
Sr.No. | Method & Description |
---|---|
1 | public void start() Starts the thread in a separate path of execution, then invokes the run() method on this Thread object. |
2 | public void run() If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object. |
3 | public final void setName(String name) Changes the name of the Thread object. There is also a getName() method for retrieving the name. |
4 | public final void setPriority(int priority) Sets the priority of this Thread object. The possible values are between 1 and 10. |
5 | public final void setDaemon(boolean on) A parameter of true denotes this Thread as a daemon thread. |
6 | public final void join(long millisec) The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. |
7 | public void interrupt() Interrupts this thread, causing it to continue execution if it was blocked for any reason. |
8 | public final boolean isAlive() Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion. |
The preceding methods are appealing on an exacting Thread object. The subsequent process in the Thread class is static. Invoking one of the stationary methods executes the action on the now running thread.
Sr.No. | Method & Description |
---|---|
1 | public static void yield() Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled. |
2 | public static void sleep(long millisec) Causes the currently running thread to block for at least the specified number of milliseconds. |
3 | public static boolean holdsLock(Object x) Returns true if the current thread holds the lock on the given Object. |
4 | public static Thread currentThread() Returns a reference to the currently running thread, which is the thread that invokes this method. |
5 | public static void dumpStack() Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application. |
The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable −
// File Name : DisplayMessage.java // Create a thread to implement Runnable public class DisplayMessage implements Runnable { private String message; public DisplayMessage(String message) { this.message = message; } public void run() { while(true) { System.out.println(message); } } }
Following is another class that extends the Thread class
// File Name : GuessANumber.java // Create a thread to extentd Thread public class GuessANumber extends Thread { private int number; public GuessANumber(int number) { this.number = number; } public void run() { int counter = 0; int guess = 0; do { guess = (int) (Math.random() * 100 + 1); System.out.println(this.getName() + " guesses " + guess); counter++; } while(guess != number); System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**"); } }
Following is the main program, which makes use of the above-defined classes:
// File Name : ThreadClassDemo.java public class ThreadClassDemo { public static void main(String [] args) { Runnable hello = new DisplayMessage("Hello"); Thread thread1 = new Thread(hello); thread1.setDaemon(true); thread1.setName("hello"); System.out.println("Starting hello thread..."); thread1.start(); Runnable bye = new DisplayMessage("Goodbye"); Thread thread2 = new Thread(bye); thread2.setPriority(Thread.MIN_PRIORITY); thread2.setDaemon(true); System.out.println("Starting goodbye thread..."); thread2.start(); System.out.println("Starting thread3..."); Thread thread3 = new GuessANumber(27); thread3.start(); try { thread3.join(); } catch (InterruptedException e) { System.out.println("Thread interrupted."); } System.out.println("Starting thread4..."); Thread thread4 = new GuessANumber(75); thread4.start(); System.out.println("main() is ending..."); } }
This will produce the following result. You can try this example again and again and you will get a different result every time.
Starting hello thread... Starting goodbye thread... Hello Hello Hello Hello Hello Hello Goodbye Goodbye Goodbye Goodbye Goodbye .......
While doing Multithreading programming in Java, you would need to have the following concepts very handy −
Here at Intellinuts, we have created a complete Java tutorial for Beginners to get started in Java.