Process can be further divided into small tasks which refer as a Thread. If two or more tasks of a process executes concurrently, then this scenario refers as a Multithreading environment. Every thread has it's own independent path of execution. In java, there are two ways to implement multithreading -
Through implementation of Runnable interface - To create a thread, we can implement Runnable interface. This interface has a single run() method declaration, so we have to override that method. Actually, in this approach, we write a wrapper over Thread class. The objects of the class which implements Runnable interface, work as a thread of the program and run on their own execution paths.
Here is the sample code -
//This class objects will work as Threads public class RunnableExample implements Runnable { private Thread thread; public RunnableExample(String name) { //here we pass the reference whose run method should be called. thread = new Thread(this, name); //creating thread thread.start(); } public void run() { //your logic will go here System.out.println(thread.getName()); } } public class RunnableMain { public static void main(String[] args) { //Creating three objects Runnable run1 = new RunnableExample("Thread-1"); Runnable run2 = new RunnableExample("Thread-2"); Runnable run3 = new RunnableExample("Thread-3"); } }
2. Using Thread class extension - This is another approach of thread creation. But, it restricts the class to extend other classes (if required). In this approach, we extend our class to Thread class so that it's objects work as threads and run on their own separate execution paths.
Here is the sample code -
//This class objects will work as Threads public class ThreadExample extends Thread { public ThreadExample(String name) { super(name); } public void run() { //your logic will go here System.out.println(thread.getName()); } } public class ThreadMain { public static void main(String[] args) { //Creating three objects Thread t1 = new ThreadExample("Thread-1"); Thread t2 = new ThreadExample("Thread-2"); Thread t3 = new ThreadExample("Thread-3"); creating threads t1.start(); t2.start(); t3.start(); } }
this is helpful thanks a lot.
ReplyDeleteyou could have explained it better !!
ReplyDeletePlease let me know the gaps so I can add on in the next post.
ReplyDelete