View RSS Feed

Thread

Thread Creation

Rate this Entry
by , 01-08-2012 at 12:12 PM (1135 Views)
Threads can be created using one of the following methods.

• By Extending Thread class.
• By Implementing Runnable interface.

Java Code: Thread creation
class Counter extends Thread {
//method where the thread execution will start
public void run(){
//logic to execute in a thread
}
//let’s see how to start the threads
public static void main(String[] args){
Thread t1 = new Counter();
Thread t2 = new Counter();
t1.start(); //start the first thread. This calls the run() method
t2.start(); //this starts the 2nd thread. This calls the run() method
}
}

class Counter extends Base implements Runnable {
//method where the thread execution will start
public void run(){
//logic to execute in a thread
}
//let us see how to start the threads
public static void main(String[] args){
Thread t1 = new Thread(new Counter());
Thread t2 = new Thread(new Counter());
t1.start(); //start the first thread. This calls the run() method
t2.start(); //this starts the 2nd thread. This calls the run() method
}
}

Submit "Thread Creation" to Facebook Submit "Thread Creation" to Digg Submit "Thread Creation" to del.icio.us Submit "Thread Creation" to StumbleUpon Submit "Thread Creation" to Google

Updated 01-14-2012 at 06:52 PM by Thread

Categories
Tutorial

Comments