Creating a Java Thread example
Creating A Thread -
There are two ways to create threads.
1)extends Thread Class
2)implements Runnable Interface.
Example – Through the Thread Class
public class Test extends Thread{
private String msg;
Test(String msg){
this.msg=msg;
}
public void run() {
for(int x=0; x<5; x++){
System.out.println("-----"+msg);
}
}
public static void main(String[] args){
Thread thread1 = new Test("first Thread");
Thread thread2 = new Test("Second Thread");
thread1.start();
thread2.start();
}
}
Example – Through the Runnable Interface
public class Test implements Runnable{
private String msg;
Test(String msg){
this.msg=msg;
}
public void run() {
for(int x=0; x<5; x++){
System.out.println("-----"+msg);
}
}
public static void main(String[] args){
Thread thread1 = new Thread(new Test("first Thread"));
Thread thread2 = new Thread(new Test("Second Thread"));
thread1.start();
thread2.start();
}
}
Runnable Interface is preferred because Interface support multiple inheritance.
There are two ways to create threads.
1)extends Thread Class
2)implements Runnable Interface.
Example – Through the Thread Class
public class Test extends Thread{
private String msg;
Test(String msg){
this.msg=msg;
}
public void run() {
for(int x=0; x<5; x++){
System.out.println("-----"+msg);
}
}
public static void main(String[] args){
Thread thread1 = new Test("first Thread");
Thread thread2 = new Test("Second Thread");
thread1.start();
thread2.start();
}
}
Example – Through the Runnable Interface
public class Test implements Runnable{
private String msg;
Test(String msg){
this.msg=msg;
}
public void run() {
for(int x=0; x<5; x++){
System.out.println("-----"+msg);
}
}
public static void main(String[] args){
Thread thread1 = new Thread(new Test("first Thread"));
Thread thread2 = new Thread(new Test("Second Thread"));
thread1.start();
thread2.start();
}
}
Runnable Interface is preferred because Interface support multiple inheritance.
Comments
Post a Comment