Threads
Multiprogramming or multitasking is a process of running more than one program in a processor. Multithreading is special type of multiprogramming in which a single program is divided into several subprograms called thread. Each thread can be processed using a processor. Every program has atleast one thread.
Java programs are divided into
If a program contains only one thread then it is called Single-threaded program. If a program contains more than one thread then it is called multithreaded programs.
Uses:
Creating threads:
A new thread can be created in two ways. They are
In both methods we must override the method run() in our newly created thread. The run() is the main method of every thread.
General form:
Public void run()
a)Extending the thread class
In java there is a predefined “thread” class available in the package “java.lang”. Using this base thread we can create a new thread as follows:
Step 1: Declaring the class
Class Newthread extends Thread
{
--------
--------
}
where class, extends – keywords
Thread – classname
Newthread - name of the thread to be created.
Step 2: override the method run()
The tun() method should be inherited from the super thread class Thread and it must be overridden as follows:
Public void run()
{
----------
----------
----------
}
step 3: starting new thread:
we can start the newly created by using the method start(). General form:
Newthread t1 = new Newthread();
t1.start();
where
Newthread – already defined thread
T1 - thread object.
New – keyword
Start() – method to start run() method.
b)implementing runnable:
Runnable is a thread interface. By implementing this we can create new thread. The steps to be followed to create a new thread class is
Step 1:Declaring class
Class Newthread implements Runnable
{
----------------
----------------
----------------
}
step 2: define the method run()
The method run() is declared in the interface runnable. So we have to define the method run() in the Newthread as follows:
Public void run()
{
--------
--------
----------
}
step 3: Starting the new thread:
start the newly created thread by using the method start(). General form
Newthread t1 = new Newthread();
T1.start();
Step 4: Define a constructor:
After creating the thread we have to declare an object of type Threda in that class. Thread class has number of constructors. General form:
Thread(Runnable threadobj, String threadname);
Where, Thread – class
Runnable – interface
String – class
Threadobj – runnable object
Threadname – name of new thread
| Name* : |
|||||
| Email* : |
|||||
| Country* : |
|||||
| Phone* : |
|||||
| Subject* : |
|||||
| Upload Homework : Upload another homework (upto 5 uploads max.)
|
|||||
| Due Date |
Time |
AM/PM |
Timezone |
||
| Instructions |
|||||
|
|||||