JAVA- Creating threads

New thread can be created in two different ways:

1.      Thread class

2.      Implementing ‘runnable’

1.     Thread class: In this method we define a class that extends ‘thread’ class and overrides  its ‘run()’ method with the code required by the thread.

2.     Implementing ‘runnable’ interface: In this method we define a class that implement runnable. The runnable interface has only one method with named run() that has to be defined in the method with the code to be executed by the thread.

 

Extending the thread class: The thread class is present in the package ‘java.lang.Thread’. followings are the steps to create a thread by extending the thread class.

a. Declare the class as extending the Thread class.

b. Implement the run() method.

c. Create a thread object calls a start() method to start the thread execution.

 

The thread class can be extended as follows:

class  ExampleThread  extends Thread

{

——————

——————

}

run() method: The run() method is inherited from the Thread class and it has to be implemented in ExampleThread class as follows:

public void run()

{

—————–               // Thread code

—————–

}

Starting the Thread using start() method:

MyThread  td=new MyThread;

td.start();

The start method causes thread to move into the runnable state. The java runtime will schedule the thread by calling its rrunnableun() method.

 

Stopping and blocking the thread 

Stopping: If we want to stop a thread we may call its stop() method as follows:

ExampleThread.stop();

This statement causes the thread to move to the dead state.

Blocking: We can  suspended or blocked a thread from entering into the runnable/running state by using the followings thread methods:

sleep(): Blocked for specific time.

suspended(): Blocked until further order.

wait(): Blocked until certain conditions occurs.

Leave a Reply

Your email address will not be published. Required fields are marked *