We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 15
creating threads
Thread contain a method called run() in which the
thread’s behaviour can be implemented. Syntax of run() method is : public void run() { .................... .................... .................... } Thread can be initiated with the help of method called start(). a new thread can be created in two ways : 1 .define a class that extends Thread class and override its run() method. 2. define a class that implements Runnable interface. new class has to define the method run() of Runnable interface. The Main Thread the main thread of your program is the one that is executed when your program begins. extending the Thread class extending the Thread class it includes the following steps: 1.create a new class that extends Thread, and then to create an object of that class. 2.The extending class must override the run( ) method 3. call start( ) method to begin execution of the new thread 1. Declaring the class Syntax: class MyThread extends Thread { ...................................... ..................................... ...................................... } 2. override the run( ) method public void run() { ................................. .................................... ................................. } 3. starting new Thread to create and run an instance of thread class,write the following MyThread aThread = new MyThread (); aThread.start(); first line creates an object of class MyThread. Now the thread is in newborn state. Second line calls start() method , cause the thread to move into runnable state. When run() method is invoked ,thread is said to be in running state. Example program class A extends Thread { public void run() { for (int i=1;i<=5;i++) { System.out.println("From Thread A: i="+i); } System.out.println("Exit from A"); } } class B extends Thread { public void run() { for (int i=1;i<=5;i++) { System.out.println("From Thread B: i="+i); } System.out.println("Exit from B"); } } class ThreadTest { public static void main(String args[]) { new A().start(); new B().start(); } } o/p javac ThreadTest.java java ThreadTest
From Thread B: i=1
From Thread A: i=1 From Thread A: i=2 From Thread A: i=3 From Thread A: i=4 From Thread A: i=5 From Thread B: i=1 From Thread B: i=2 Exit from A From Thread B: i=3 From Thread B: i=4 From Thread B: i=5 Exit from B there are three threads in the program- main method in the ThreadTest class constitutes main thread and two other threads thread A and thread B. in the statement new A().start(); main thread creates and starts thread A The start() method returns back to main thread after invoking run() method and then main thread starts thread B.