Home  >  Forum  >  Core Java
Post New Query

how many ways to create thread in java


joined on
April 16,2013
Asked on August 02,2015
I am learning java thread and want to know how many way to create a thread in java. I know about "extends Thread" class. Is any other way? 
joined on
March 05,2015
Replied on August 02,2015

There are two ways to create a thread:

1-By extending Thread class

class City extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
City t1=new City();  
t1.start();  
 }  

2-By implementing Runnable interface.

class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
 }  
}  
joined on
March 15,2013
Replied on August 02,2015

In Java there are three ways to create a Thread.
1- By extending Thread class
2- By implementing Runnable interface
3- By implementing Callable interface

Example for  1- 

public class ThreadExtends extends Thread {

public void run() {
System.out.println("Java Thread-Concretepage.com");
}

public static void main(String[] args) {

ThreadExtends te = new ThreadExtends();
te.start();

System.out.println("main thread");
}
}

Example for  2- 

class JavaThreadDemo implements Runnable {

public void run() { // Always use public void run() method to call a thread

try {

for (int i = 0; i < 10; i++) {

System.out.println("new thread");
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}

}
}

class JavaThread {

public static void main(String[] args) {

Runnable run = new JavaThreadDemo();
Thread td = new Thread(run);
td.start();
System.out.println("main thread");

}

}

 Example for  3-    http://www.concretepage.com/java/java-callable-example
joined on
March 22,2013
Replied on August 02,2015

In Java 1.5 there is another way to invoke a thread. That is by “ExecutorService”. All these classes are from the “java.util.concurrent” package. There are various ways to create a “ExecutorService” using “Executors” factory class. The following is one of the way to create “ExecutorService”..

ExecutorService es= Executors.newSingleThreadExecutor();
RunnableImpl r = new RunnableImpl();
Future fu=es.submit(r);

Write Answer



Sitewide-Feb4of4234x60





Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us