Saturday 23 January 2016

Multithreading in Java | How to create threads in Java | Creating Multiple Threads in Java

                   In this post, we will see Multithreading in Java | How to create threads in Java | Creating Multiple Threads in Java | multithreading in java,how to create threads in java,creating threads in java,creating multiple threads in java,runnable interface in multithreading,thread class in java,thread class vs runnable interface,thread class and runnable interface in java,thread class methods in java.

                   In Java, there are two ways of creating threads:

1. By implementing interface Runnable

2. By extending class Thread  

Watch this video to know multithreading in java:


Watch on YouTube: https://www.youtube.com/watch?v=8s3JaxpQDPI

             Lets see an example for each way-



1. 1. Creating multiple threads in Java by implementing interface Runnable

Program:(progbyrunnable.java)

class T implements Runnable
{
  public void run()
  {
  System.out.println("Thread is running");
  }
}

class T1 implements Runnable
{
  public void run()
  {
  System.out.println("New Thread is running");
  }
}

class progbyrunnable
{
  public static void main(String args[])
  {
  T p=new T();
  T1 p1=new T1();
  Thread t1=new Thread(p);
  Thread t2=new Thread(p);
  Thread t3=new Thread(p1);
  t1.start();
  t2.start();
  t3.start();
  }
}

How To Run:
To Compile:
javac progbyrunnable.java

To Run:
java progbyrunnable

Output:


2. Creating multiple threads in Java by extending class Thread

Program:(progbythread.java)

class T extends Thread
{
  public void run()
  {
  System.out.println("Thread is running");
  }
}

class T1 extends Thread
{
  public void run()
  {
  System.out.println("New Thread is running");
  }
}

class progbythread
{
  public static void main(String args[])
  {
  T p1=new T();
  T p2=new T();
  T1 p3=new T1();
 
  p1.start();
  p2.start();
  p3.start();
  }
}

How To Run:
To Compile:
javac progbythread.java

To Run:
java progbythread 

Output:

 




No comments:

Post a Comment