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

Hibernate auto increment with example

how to count the page views by using JSP

Multithreading in java with example

How to retrieve data from table by using JDBC with example

Prime, Fibonacci and Factorial number with example in java

How to insert images into database using JDBC?

How to sort list of objects in java with examples

String interview questions and answers

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Store file into table by using JDBC with example