How Thread can created in Java Programming?
Previous | Home | Next |
There are two main ways of creating a thread
1.Extend the thread class
2.Implement the runnable interface:-Runnable is actually an interface, with the single run() method that we must provide.
creating a thread like this in java
Thread thread = new Thread();
To start the thread you will call its start() method, like this:
thread.start();
public class MyThread extends Thread
{
/**
* This method is executed when the start() method is called on the thread
* so here you will put the 'thread code'.
*/
public void run() {
System.out.println("Thread executed!");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Thread thread = new MyThread();
thread.start();
}
}
Implementing the Runnable interface:
public class MyRunnable implements Runnable {
/**
* As in the previous example this method is executed
* when the start() method is called on the thread
* so here you will put the 'thread code'.
*/
public void run() {
System.out.println("Thread executed!");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//create a Thread object and pass it an object of type Runnable
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
Previous | Home | Next |