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)
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)
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();
}
}
{
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();
}
}
{
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();
}
}
No comments:
Post a Comment