0% found this document useful (0 votes)
2 views

threadinjava

The document discusses the concept of threads and multithreading in Java, explaining how threads allow concurrent execution of code within a single program. It outlines methods for creating threads by extending the Thread class or implementing the Runnable interface, along with examples demonstrating their usage. Additionally, it covers thread management, including starting, stopping, and naming threads, as well as the importance of synchronization to prevent data inconsistencies when multiple threads access shared resources.

Uploaded by

vanidupati22
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

threadinjava

The document discusses the concept of threads and multithreading in Java, explaining how threads allow concurrent execution of code within a single program. It outlines methods for creating threads by extending the Thread class or implementing the Runnable interface, along with examples demonstrating their usage. Additionally, it covers thread management, including starting, stopping, and naming threads, as well as the importance of synchronization to prevent data inconsistencies when multiple threads access shared resources.

Uploaded by

vanidupati22
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Threads and Multithreaded in java:

Senior Lecturer Hana Rasheid


All Java programs other than simple console-based applications are
multithreaded; the problem is that the Abstract Windowing Toolkit (AWT)
processes operating system (OS) events on its own thread, so your listener
methods actually run on the AWT thread. These same listener methods typically
.access objects that are also accessed from the main thread

Threads enable a single program to run multiple parts of itself at the same time.
For example, one part of a program can display an animation on the screen
while another part builds the next animation to be displayed.
Threads do not make copies of the entire parent process. Instead, only the code
needed is run in parallel. This means that threads can be started quickly because
they don't have all of the overhead of a complete process. They do, however,
have complete access to all data of the parent process. Threads can read and/or
write data that any other thread can access.

Uses of Threads
Threads are useful programming tools for two main reasons.
1-First, they enable programs to do multiple things at one time. This is useful
for such activities as letting a user do something while something else happens
in the background.
2-Second, threads enable the programmer to concentrate (give attention to) on
program functionality without worrying about the implementation of
multitasking schemes. A programmer can simply spin off (follow-up) another
thread for some background or parallel operation without being concerned about
inter process communications.

Declaring Threads
To create classes that make use of threads, you can
1- extend the class Thread or
2- implement the interface Runnable.
Both yield (give in) the same result. By implementing Runnable, existing
classes can be converted to threads without having to change the classes on
which they are based.

1-Creating Threads by Extending Thread


Example (1): In this example, a thread is created that will write an incrementing
counter to the screen. It will continue to count until the main routine receives a
character from the keyboard, at which time the counting thread stops. This

1
means you can press any key on the keyboard followed by the Enter key or
press only the Enter key to stop the thread from counting.
public class thread class
{
public static void main (String args [ ])
{
CntThread cntThread; //declare thread
cntThread = new CntThread(); //create thread
cntThread.start( //start thread running
try
{
;)(System.in.read
wait for keyboard input/ }
catch(java.io.IOException e)
{
cntThread.stop( ); //stop thread
}
}
class CntThread extends Thread
{
) (public void run
{
;int ix = 0
while (true)
{
System.out.println("running, ix = " + ix++);
try {
;Thread.sleep(1000)
sleep 1 second// }
} {catch(InterruptedException e)
end while//}
end run//}
end class//}
:The output is
running, ix = 0
running, ix = 1
running, ix = 2
running, ix = 3
2
running, ix = 4
running, ix = 5
running, ix = 6
running, ix = 7
running, ix = 8
running, ix = 9
running, ix = 10
running, ix = 11
running, ix = 12
running, ix = 13
running, ix = 14

2-Creating Threads by Implementing Runnable interface.


The second way to create a thread is by implementing the Runnable interface.
Example(2): the following code creates a thread that increments a counter until
a character is entered from the keyboard:
:Sol
;*.import java.applet
;*.import java.awt
public class MyApplet extends Applet implements Runnable
{
;int ix = 0
;Thread mainThread
;CntThread cntThread
) (public void start
{
if (mainThread == null)
{
;mainThread = new Thread(this)
mainThread.start( ); //start main thread
}
}
) (public void run
{
cntThread = new CntThread(this); //create CntThread instance
cntThread.start( ); //start cntThread instance
}

3
public boolean keyDown(Event evt, int key) //process key press
{
cntThread.stop( ); //stop cntThread instance
;return(true)
}
public void paint(Graphics g)
{
g.drawString("running, ix = " + ix, 10,20); //write count to screen
}
}
{ class CntThread implements Runnable

;MyApplet parent
;boolean loop
;Thread cntThread
public CntThread(MyApplet p) //constructor for CntThread
{
parent = p; //save parent instance
}
) (public void start
{
if (cntThread == null)
{
cntThread = new Thread(this); //create counting thread
cntThread.start( ); //start counting thread
}
}
) (public void stop
{
loop = false; //set value to exit main while loop
}
) (public void run
{
;loop = true
{ while (loop == true)
parent.ix++; //incremen t counter
parent.repaint(); //repaint screen

4
{ try
;Thread.sleep(1000)
sleep 1 second// }
}{ catch(InterruptedException e)
}
}}
Steps required in creating a new thread
Creating and running a thread in Java is simple, just follow these steps:
1. Define a class that implements the Runnable interface. The interface has a
single method - called run( ) - that must be defined.
2. Place the code that the thread should execute in run( ). Remember to handle
exceptions.
3. Create an instance of the class.
4. Create a Thread object and pass the class instance as the constructor
argument.
5. Call the start( ) method of the Thread object to start the thread.
Creating thread by implementing Runnable interface

.Let your class implement “Runnable” interface .1


Now override the “public void run()” method and write your logic there .2
.(This is the method which will be executed when this thread is started)
That’s it, now you can start this thread as given below
Create an object of the above class .1
Allocate a thread object for our thread .2
.Call the method “start” on the allocated thread object
Example: In this example, we will create two threads “FirstThread” and
“SecondThread”. Both of these threads will display numbers 1, 2, 3…10 with
a one second delay in displaying the next number. ThreadDemo class will be
.”starting these threads “FirstThread” and “SecondThread

First Thread
.This class is made as a thread by implementing "Runnable" interface //
class FirstThread implements Runnable
{
This method will be executed when this thread is executed //
) (public void run
{
Looping from 1 to 10 to display numbers from 1 to 10//
for ( int i=1; i<=10; i++)

5
{
Displaying the numbers from this thread//
;System.out.println( "Messag from First Thread : " +i)
taking a delay of one second before displaying next number*/
,Thread.sleep(1000);" - when this statement is executed " **
this thread will sleep for 1000 milliseconds (1 second) *
.before executing the next statement *
,Since we are making this thread to sleep for one second *
we need to handle "InterruptedException". Our thread *
may throw this exception if it is interrupted while it *
;is sleeping.sleep (1000) *
catch (InterruptedException interruptedException)
{
Interrupted exception will be thrown when a sleeping or waiting */
.thread is interrupted*
/*
+ "System.out.println( "First Thread is interrupted when it is sleeping
;)interruptedException
}
}
Second Thread
.This class is made as a thread by implementing "Runnable" interface //
class SecondThread implements Runnable
{
This method will be executed when this thread is executed //
) (public void run
Looping from 1 to 10 to display numbers from 1 to 10//{
for ( int i=1; i<=10; i++)
{
;System.out.println( "Messag from Second Thread : " +i)

taking a delay of one second before displaying next number*/

,Thread.sleep(1000);" - when this statement is executed " *


this thread will sleep for 1000 milliseconds (1 second) *
.before executing the next statement *
,Since we are making this thread to sleep for one second *

6
we need to handle "InterruptedException". Our thread *
may throw this exception if it is interrupted while it *
.is sleeping *
;d.sleep(1000)/*
}
catch (InterruptedException interruptedException)
{
Interrupted exception will be thrown when a sleeping or waiting *
/.thread is interrupted *
System.out.println( "Second Thread is interrupted when it is sleeping"
;+interruptedException)
}
}
”Main Class which starts the “First Thread” and “Second Thread

public class ThreadDemo


{
public static void main(String args[])
{
Creating an object of the first thread//
;)(FirstThread firstThread = new FirstThread
Creating an object of the Second thread//
;)(SecondThread secondThread = new SecondThread
Starting the first thread//
;Thread thread1 = new Thread(firstThread)
;)(thread1.start
Starting the second thread//
;Thread thread2 = new Thread(secondThread)
;)(thread2.start
}
}

7
Output of ThreadDemo

Example(3):
public class ExampleThread extends Thread{
private String name;
private String text;
private final int REPEATS = 8;
private final int DELAY = 200;
public ExampleThread( String aName, String aText )
{
name = aName;
text = aText;
}
public void run( )
{
try {
for ( int i = 0; i < REPEATS; ++i )
{

8
System.out.println( name + " says " + text );
Thread.sleep( DELAY );
}
}
catch( InterruptedException exception )
{
System.out.println( "An error occurred in " + name );
}
finally {
System.out.println( name + " is quiting..." );
}
}
}
class ThreadTest
{
public static void main( String[ ] args ) {
ExampleThread et1 = new ExampleThread( "Thread #1", "Hello
World!" );
ExampleThread et2 = new ExampleThread( "Thread #2", "Good
Morning!" );
Thread t1 = new Thread( et1 );
Thread t2 = new Thread( et2 );
t1.start( );
t2.start( );
}
}
run:
Thread #1 says Hello World!
Thread #2 says Good Morning!
Thread #2 says Good Morning!
Thread #1 says Hello World!
Thread #1 says Hello World!
Thread #2 says Good Morning!
Thread #1 says Hello World!
Thread #2 says Good Morning!
Thread #2 says Good Morning!
Thread #1 says Hello World!
Thread #2 says Good Morning!
Thread #1 says Hello World!
Thread #2 says Good Morning!
Thread #1 says Hello World!
Thread #1 says Hello World!
Thread #2 says Good Morning!

9
Thread #2 is quiting...
Thread #1 is quiting...

new and the Instantiation of Threads


Instances of threads are created using the standard new keyword. Arguments to
new can either use the Thread class explicitly, as in
;mainThread = new Thread(this)-1
or specify a class that is a subclass of Thread, like this:
;)(mainThread = new MyThreadClass-2
In the first example, the current instance, this, of an object is initialized as a
thread. Any object, however, can be passed as an argument to the Thread class.
Note that the Thread class has few constructors. If additional constructor types
are needed, creating a subclass of Thread with the needed constructors is quite
useful.

Destroying a Thread

You can control the execution of a thread in several ways using the stop, start,
and destroy methods. The object remains in existence as long as the object is
referenced somewhere, even if stop is invoked.
It is not necessary to explicitly destroy the thread object. Java's garbage
collector takes care of this detail. If it is necessary to give the garbage-collection
process a helping hand, make sure all references are removed to the thread
object. The simplest way to do this is to assign the value null to all variables
containing thread references, as in the following example:
;) (Thread myThread = new Thread
;)(myThread.start
;)(myThread.stop
;myThread = null
In this example, the thread object is instantiated with new. The thread is then
started and stopped. Finally, null is assigned to the variable containing the
thread instance.

Thread Methods:
All Java threads implement four methods: init, run, start, and stop.
These are default methods in the Thread class; if a class implements
Runnable, these methods must be declared explicitly.

10
Init:The init method is called the first time a thread is started. It is usually
used for initialization of objects, but can be used in any way the programmer
sees fit. Here is an example of an init method:
public void init( ) // This method simply assigns a value of zero to
the index variable.
{
index = 0;
}
Start: The start method is called to start a thread execution. This method
usually contains the code for actually creating and starting a thread.
Example( ): This method checks to see if a thread has not yet be
Example( ): This method checks to see if a thread has not yet been created by
testing whether the thread object mainThread is null. If it is not, a new thread
object is created using new, and then the thread itself is started by calling the
object's start method.
) (public void start
{
if (mainThread == null)
{
;new mainThread = Thread(this)
;) (mainThread.start
}
}
Stop: The stop method contains the code needed to stop a thread's execution,
often in the form of generating a signal that will be caught by all threads and
that causes them to exit. stop also can change an object that causes a calling
loop in the run method to exit.
Example( ):This method simply sets a variable to false .
) (public void stop
{
;loop = false
}
Run:The run method is similar in function to main in C or C++. run contains
the main body of code to be executed by a thread.
Example( ):
) (public void run
{
;loop = true

11
while (loop == true)
{
;System.out.println("index = " + index++)
{ try
;Thread.sleep(1000)
}
}{catch(InterruptedException e)
}
}
The body of this method consists of the initialization of the loop variable and a
while loop that will continue executing until loop no longer has a value of
true. The body of the loop prints out the value of the index variable to the
screen and then sleeps for one second.

Named Threads
Java provides a means for assigning names to threads. Names can consist of any
valid Java string. Naming threads makes it convenient to distinguish one thread
from another and enables a parent process to query a thread for its name. A
thread can be assigned a name at creation time or at any point thereafter.
Threads can also be renamed at any time.
To assign a thread a name at creation time, simply use a Thread constructor
that accepts a string as an additional argument, like this:
Thread myThread = new Thread(this."My first named
;thread")
In this example, the thread is instantiated by new and assigned a name of "My
first named thread".
The getName Method:You can query a thread for its name using the
getName method. getName returns the name associated with a specified
thread object, as in the following example:
System.out.println("The name of this thread is " +
;myThread.getName())
This example prints out the name assigned to the thread object myThread.
Using the previous example, this statement would print the following to the
screen:
The name of this thread is My first named thread
A thread can also query for its own name in the same way:
;System.out.println("My name is " + this.getName())

12
The setName Method
You can set or change a thread name after creation using the setName method.
The parent process, the thread itself, or any other method that has access to the
thread object can do this. Following is an example of changing a thread name
using setName:
;myThread.setName("My newly renamed first thread")
This example changes the name of the thread from "My first named
thread" to "My newly renamed first thread".

Synchronization of Threads
Multiple threads can access the same object or method because threads are not
independent processes with complete copies of data objects. However, there is
no guarantee which thread will access an object at a given time, which can lead
to unpredictable (random) results. In situations when this is not acceptable, use
the Java synchronization logic. The keyword that provides this logic is
synchronized.
The synchronized Keyword : The synchronized keyword is used to lock an
object long enough to execute a block of code. No other thread can make
changes to the specified object while the block of code is being executed.
:) (Example
)(public void printIndex
{
syncronized(index)
{
;++index
;System.out.println("index = " + index)
}
}
In this example, the printIndex method contains a synchronized block of code.
In this block, the object index is locked while the block of code making up the
body of the synchronized statement is executed. The increment of index and the
printing of the value of index are contained inside the block. This ensures that
the value of index is printed to the screen without having to worry that some
other thread incremented index before it was printed. synchronized also can be
used as a modifier for methods, thus ensuring that only one thread at a time
executes the method. The previous example could be rewritten using this
: construct as
{ )(public syncronized void printIndex
;++index
13
;System.out.println("index = " + index)
}
LAB:Write a program that Using thread named (student) which print the
message ( I am a student) 10 times and sleep (2000) second and thread named
(exam) which print the message(I have java exam ) 10 times and sleep (4000)
.seconds
:Reference
java “How to program”,Author: H.M.Deitel
Edition &year public : Sixth edition ,2006

14

You might also like