Java Thread Methods

Sleep and Interrupt Method in Threads - Demo
"
Join Method in Threads - Demo
"

Introduction to Thread Class Methods in Java

Thread methods in Java are used to manage and control the execution of threads. There are many different thread methods available, but some of the most common ones include:

  • `start()`: Starts the execution of the thread.
  • `run()`: The code that the thread will execute.
  • `sleep()`: Causes the thread to sleep for a specified amount of time.
  • `join()`: Causes the current thread to wait until the specified thread has finished executing.
  • `interrupt()`: Causes the specified thread to be interrupted.

Thread methods can be used to achieve a variety of different goals, such as:

  • Creating multiple threads to perform tasks simultaneously: This can improve the performance of Java applications by allowing multiple tasks to run at the same time.
  • Synchronizing access to shared resources: This can help to prevent race conditions and other errors that can occur when multiple threads are accessing the same resource at the same time.
  • Controlling the execution of threads: This can be used to implement features such as thread priorities and thread pools.

Here is an example of how thread methods can be used to create a simple thread that prints a message to the console:


public class ThreadExample {
  public static void main(String[] args) {
      Thread thread = new Thread(() -> {
          System.out.println("Hello from the thread!");
      });

      thread.start();
  }
}

When you run this code, it will create a new thread and start it executing. The new thread will then print the message "Hello from the thread!" to the console.

Thread methods can be a complex topic to learn, but they are an essential part of Java programming. By understanding the basics of thread methods, you can write more efficient and responsive Java applications.

Exercises

Code for Writing numbers to two different files using Threads


  package sampleproject;
  import java.util.*;
  import java.io.*;
  public class democlass{	
      
    
    public static void main(String[] args){	
    
        filewrite1 f1 = new filewrite1();
        filewrite2 f2 = new filewrite2();
        f1.start();
        f2.start();
    }
  }
  
  class filewrite1 extends Thread
  {
  
    @Override
    public void run() {
        
        File obj = new File("file1.txt");
        try {
        FileOutputStream fout = new FileOutputStream(obj);
        System.out.println("writing to file1");
        for(int i=0;i<10000;i++)
        {
          System.out.println("Thread1 write"+i);
          fout.write(i);
        }
        fout.close();
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }   
    }
  }
  
  class filewrite2 extends Thread
  {
  
    @Override
    public void run() {
        
        File obj = new File("file2.txt");
        try {
        FileOutputStream fout1 = new FileOutputStream(obj);
        System.out.println("writing to file2");
        for(int i=0;i<10000;i++)
        {  
          System.out.println("Thread2 write"+i);
          fout1.write(i);
        }
        fout1.close();
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  } 

Code for putting a thread to sleep for 6000 milli seconds


  package sampleproject;
  import java.util.*;
  import java.io.*;
  public class democlass{	
      
    public static void main(String[] args){	
    
        filewrite1 f1 = new filewrite1();
      //  filewrite2 f2 = new filewrite2();
        f1.start();
      //  f2.start();
    }
  }
  
  class filewrite1 extends Thread
  {
  
    @Override
    public void run() {
        
        File obj = new File("file1.txt");
        try {
        FileOutputStream fout = new FileOutputStream(obj);
        System.out.println("writing to file1");
        for(int i=0;i<10000;i++)
        {
          System.out.println("Thread1 write"+i);
          if(i==500)
          {
            System.out.println("thread sleep mode");
            filewrite1.sleep(6000);
          }
          fout.write(i);
        }
        fout.close();
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  } 

Code for setting priority to Threads using the setPriority Method


  package sampleproject;
  import java.util.*;
  import java.io.*;
  public class democlass{	
      
    public static void main(String[] args){	
    
        filewrite1 f1 = new filewrite1();
        filewrite2 f2 = new filewrite2();
        f2.setPriority(10);
        f1.setPriority(1);
        f1.start();
        f2.start();
    }
  }
  
  class filewrite1 extends Thread
  {
    @Override
    public void run() {
        byte b[]= {104,105,106,107,108,109,110,111,112,113,114,115};
        File obj = new File("file1.txt");
        try {
        FileOutputStream fout = new FileOutputStream(obj);
        System.out.println("writing to file1");
        fout.write(b);
        fout.close();
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  
  class filewrite2 extends Thread
  {
    @Override
    public void run() {
        byte b[]= {116,117};
        File obj = new File("file1.txt");
        try {
        FileOutputStream fout1 = new FileOutputStream(obj);
        System.out.println("writing to file2");
        fout1.write(b);
        fout1.close();
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  } 

Demo Code for the use of Sleep and Interrupt Methods in Threads in Java


  import java.util.Scanner;
  public class Satish20BCE001{
    public static void main(String[] args){
      
      //demo on the sleep method for Thread
      test t = new test();
      Thread thr1 = new Thread(new Runnable() {
        
        @Override
        public void run() {
              t.display(); 			
          }
      });
      thr1.start();
      thr1.interrupt(); //interrupt will wake up the thread thats sleeping
      System.out.println(thr1.isInterrupted());
  }
  }
  
  class test
  {
    public void display() {
      for(int i=1;i<=50;i++)
      {
        System.out.println(i);
          if(i==5)
          {
          try {
            Thread.sleep(10000);
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            System.out.println("Exception handled here");
          } //this thread will be in sleep state for 10000
        }
      }
    }
  } 

Demo Code for the use of Join Method in Threads. Join will ensure the completion of the Thread. Thread1 and Thread 2 will generate the even and odd numbers. Thread 3 will print the results.


  import java.util.InputMismatchException;
  import java.util.Scanner;
  
  public class Satish20BCE001{
  public static void main(String[] args) throws InterruptedException {
    
    arrayadd arr = new arrayadd();
    Thread thr1 = new Thread(new Runnable() {
      
      @Override
      public void run() {
        // TODO Auto-generated method stub
        arr.generateeven();
      }
    });
    Thread thr2 = new Thread(new Runnable() {
      
      @Override
      public void run() {
        arr.generateodd();
      }
    });
    
    Thread thr3 = new Thread(new Runnable() {
      
      @Override
      public void run() {
        arr.displayArrays();
      }
    });
    thr1.start();
    thr2.start();
    thr1.join();
    thr2.join();
    thr3.start();
  }
  
  }
  
  class arrayadd
  {
  int even[] = new int[50];
  int odd[] = new int[50];
  
  public void generateeven()
  {
    int j=0;
    for(int i=1;i<=100;i++)
    {
      if(i%2==0)
      {   System.out.println("Populating even numbers");
        even[j]=i;
        j++;
      }
    }
  }
  public void generateodd()
  {
    int j=0;
    for(int i=1;i<=100;i++)
    {
      System.out.println("Populating odd numbers");
      if(i%2!=0)
      {
        odd[j]=i;
        j++;
      }
    }
  }
  
  public void displayArrays() {
    System.out.println("Displaying the arrays");
    for(int m:even)
    {
      System.out.println(m);
    }
    for(int k:odd)
    {
      System.out.println(k);
    }
  }
  }