Monday 5 October 2020

Java program to create ODDEVEN thread using Runnable Interface

Threads are the lightweight processes. 
Java supports thread-based multitasking. 
Thread-based multi-tasking means a single program executing several tasks in the form of threads. 
The advantage of thread-based multitasking are: 
1) threads share the same address space
2) threads cooperatively share the same process 
3) inter-thread communication is inexpensive 
4) context-switching from one thread to another is not time-consuming 

 Threads can be created using one of the following two methods: 
 1) By extending Thread class in java.lang package 
 2) By implementing the Runnable interface 

In the following program, two threads are created: one thread will display all the even numbers in the range 0 to 10 while the second thread will display all the odd numbers in the range 0 to 10. The threads are created by implementing the runnable interface.

 Program 

//Program to create two threads 
class EvenThread implements Runnable
{
   Thread T;
    String n;

   EvenThread(String name)
   {
       n=name;
       T = new Thread(this, n);
    System.out.println("New thread: " + T);
    T.start();                     // Start the thread
  }

  // This is the entry point for thread.
  public void run() {
    try {
      for(int i = 0; i<=10; i++) {
         if (i%2==0)
        System.out.println(n + ": " + i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println(n + "Interrupted");
    }
    System.out.println(n+ " exiting.");
  }
}

class OddThread implements Runnable
{
   Thread T;
    String n;

   OddThread(String name)
   {
       n=name;
       T = new Thread(this, n);
    System.out.println("New thread: " + T);
    T.start(); // Start the thread
  }

  // This is the entry point for thread.
  public void run() {
    try {
      for(int i = 0; i<=10; i++) {
         if (i%2!=0)
        System.out.println(n + ": " + i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println(n + "Interrupted");
    }
    System.out.println(n+ " exiting.");
  }
}

class Thread_OddEven
 {
  public static void main(String args[]) 
 {
    OddThread o=new OddThread("Odd"); // start threads
    EvenThread e=new EvenThread("Even");
    
    try 
   {
         e.T.join();
         o.T.join();
        
     } catch (InterruptedException e1) {
      System.out.println("Main thread Interrupted");
    }
   
    System.out.println("Main thread exiting.");
  }
}


OUTPUT 
D:\Java\Programs>java Thread_OddEven
New thread: Thread[Odd,5,main]
New thread: Thread[Even,5,main]
Even: 0
Odd: 1
Even: 2
Odd: 3
Even: 4
Odd: 5
Even: 6
Odd: 7
Even: 8
Odd: 9
Even: 10
Odd exiting.
Even exiting.
Main thread exiting.

No comments:

Post a Comment