Wednesday, June 24, 2009

How to Create a Thread


There are two ways to create a thread.
1) Using Thread class
2) Using Runnable interface

Using Thread class:

// This class extends Thread
class SampleThread extends Thread {
// This method is the entry point of thread. It is called when thread runs.
public void run() {
}
}

// Create and start the thread
Thread thread = new SampleThread();
thread.start();


Using Runnable interface:

class SampleThread implements Runnable {
// This method is called when the thread runs
public void run() {
}
}

// Create the object with the run() method
Runnable runnable = new SampleThread();

Thread thread = new Thread(runnable);

// Start the thread
thread.start();

0 comments:

 

Sample Java Codes Copyright © 2008 Green Scrapbook Diary Designed by SimplyWP | Made free by Scrapbooking Software | Bloggerized by Ipiet Notez