Skip to main content

how to create our own thread in java with example

To create user defined thread in java, create a class that extends Thread or implements Runnable interface. Both of the Thread class and Runnable interface are available in java.lang package.
class MyClass extends Thread
             OR
class MyClass implements Runnable

        •  Now in this class, write a run() method as,
public void run(){
    statements;
}

       by default, this run() method is recognised and executed by a thread when you started a thread.
       •   Create an object of MyClass, So that the run() method is available for execution.
MyClass obj = new MyClass();

      •   Now, Create a thread and attach the thread to the object obj.
Thread t = new Thread(obj);

      •   Run the thread. For this purpose, we should use start() method of Thread class.
t.start();

         Now, the thread will start execution on the object of MyClass. In that object, run() method is found, hence it will execute the statements inside that run() method.

Example:
          Let us write a program to create and run a thread.
package com.javatbrains.threads;

class MyClass extends Thread{

     public void run(){
          for(int i=0;i<5;i++){
              System.out.print(i+" , ");
          }
     }
    
}

public class MyThread{
    
     public static void main(String[] arga){
          //Creating an object for MyClass
          MyClass obj = new MyClass();
          //Create Thread and attach it to the Object of MyClass
          Thread t = new Thread(obj);
          //now run the thread on the object.
          t.start();
     }
}

OutPut:
     0 , 1 , 2 , 3 , 4 ,

How to terminate a thread?
         A thread will terminate automatically when it will come out of run() method. To terminate the thread on our own, we have to device our logic. For this purpose, the following steps can be used.

           •    Create a boolean type variable and initialize it to false.
boolean stop = false;
           •    Let us assume that we will want to terminate the thread when the user presses <Enter> key. So, when the user presses enter button, make the boolean type variable as true.
stop = true;
           •     Check this variable in run() method and when it is true, make the thread return from the run() method.
public void run(){
    if(stop == true) return;
}

Example:
          Let us write a program how to stop a thread  by pressing Enter button.
package com.javatbrains.threads;

import java.io.IOException;

class MyClass extends Thread {
     boolean stop = false;

     public void run() {
          for (int i = 0; i < 10000000; i++) {
              System.out.print(i + " , ");
              if(stop)return;
          }
     }

}

public class MyThread {

     public static void main(String[] arga) throws IOException {
          // Creating an object for MyClass
          MyClass obj = new MyClass();
          // Create Thread and attach it to the Object of MyClass
          Thread t = new Thread(obj);
          // now run the thread on the object.
          t.start();
          //Stops the thread when enter key pressed
          System.in.read();
          obj.stop = true;
     }
}
OutPut:
         0 , 1 , 2 , 3 , 4 ,

Single tasking using a thread
        A thread can be employed to execute one task at a time. Suppose there are 3 tasks to be executed. We can create a thread and pass 3 tasks one after another to the thread.  For this purpose we will write all these tasks separately in separate methods: task1(), task2(),task3(). Then these methods should be called from run() method.

Example: Write an example which will show single tasking with thread? Which will also shows an example of creating a thread with Runnable interface?
package com.javatbrains.threads;

class MyThread1 implements Runnable{

     @Override
     public void run() {
          task1();
          task2();
          task3();
     }
    
     void task1(){
          System.out.println("This is task1");
     }
     void task2(){
          System.out.println("This is task2");
     }
     void task3(){
          System.out.println("This is task3");
     }
    
}

public class SingleTaskWithThread {

     public static void main(String[] args) {
          MyThread1 obj = new MyThread1();
          Thread t = new Thread(obj);
          t.start();
     }

}
OutPut:
     This is task1
     This is task2
     This is task3

Multitasking using thread

        As normal meaning of multitasking is executing two or more tasks at the same time. To perform multiple tasks execution we need to create multiple threads and need to add each thread with each task for simultaneous execution.  Running more than one thread is called multithreading in java.

Example:  Write a program for two threads working simultaneously on two objects.
package com.javatbrains.threads;

class MyThread2 implements Runnable{
     String str;
     public MyThread2(String str){
          this.str = str;
     }
    
     @Override
     public void run() {
          for(int i=0;i<=10;i++){
              System.out.println(str +" : "+i);
              try{
                   Thread.sleep(2000);
              }catch(InterruptedException ie){
                   ie.printStackTrace();
              }
          }
     }
    
}

public class MultiTaskingUsingThread {
    
     public static void main(String[] args) {
          //Create two objects to represent two tasks
          MyThread2 obj1 = new MyThread2("Cut the ticket");
          MyThread2 obj2 = new MyThread2("Show the seat");
         
          //Create two threads and attach them to objects
          Thread t1 = new Thread(obj1);
          Thread t2 = new Thread(obj2);
         
          //Start the threads
          t1.start();
          t2.start();
     }
    
}
OutPut:
     Show the seat : 0
     Cut the ticket : 0
     .
     .
     Show the seat : 10
     Cut the ticket : 10

Comments

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...