Monday, 16 January 2017

What are the two ways of creating thread?

There are two ways to create a new thread.
Extend the Thread class and override the run() method in your class. Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution. 

e.g.

public class NewThread extends Thread {
public void run() {
// the code that has to be executed in a separate new thread goes here
}

public static void main(String[] args) {
NewThread c = new NewThread();
c.start();
}
}
Implements the Runnable interface. The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created. e.g. class
public class NewThread implements Runnable {
public void run() {
// the code that has to be executed in a separate new thread goes here
}

public static void main(String[] args) {
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}
}

No comments:

Post a Comment