0% found this document useful (0 votes)
17 views13 pages

Java Multi-Threading Basics Explained

Uploaded by

Akshatha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views13 pages

Java Multi-Threading Basics Explained

Uploaded by

Akshatha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Dept.

of CS 1 JSSCW

Threading
Java is a multi-threaded programming language which means we can develop multi-
threaded program using Java. A multi-threaded program contains two or more parts that can
run concurrently and each part can handle a different task at the same time making optimal
use of the available resources.
By definition, multitasking is when multiple processes share common processing resources
such as a CPU. Multi-threading extends the idea of multitasking into applications where you
can subdivide specific operations within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
A thread is a light-weight smallest part of a process that can run concurrently with the
other parts (other threads) of the same process.
Figure below illustrates java program with four threads one main and three others. The main
thread is actually a main method module, which is designed to create and start the other
three thread namely A, B and C. Once initiated by the main thread, the threads A,B and C
run concurrently and share the resources jointly.

Creating a thread:
Threads are implemented in the form of objects that contain a method called run( ). The run( )
method makes up the entire body of the thread and is the only method in which thread
behaviours can be implemented. The run method is as follows
public void run( )
{
-------------------
------------------- (Statement for implementing thread)
-------------------
}
Dept. of CS 2 JSSCW

The run( ) method should be invoked by an object of the concerned thread. This can be
achieved by creating the thread and initiating with the help of another thread method called
start( ). A new thread can be created in two ways.
1) By extending Thread class.
2) By implementing Runnable interface.
Create a Thread by Extending a Thread Class
The second way to create a thread is to create a new class that extendsThread class using the
following two simple steps. This approach provides more flexibility in handling multiple
threads created using available methods in Thread class.
Step 1 Declaring a thread class
The thread class can be extended as fallows
class mythread extends Thread
{
---------------------
---------------------
----------------------
}
Step 2 implementing a run( ) method
You will need to override run( ) method available in Thread class. This method provides an
entry point for the thread and you will put your complete business logic inside this method.
Following is a simple syntax of run() method −
public void run( )
{
---------------------
---------------------
----------------------
}

Step 3 Starting new thread


Once Thread object is created, you can start it by calling start() method, which executes a
call to run( ) method. Following is a simple syntax of start() method −
mythread t1=new mythread()
[Link]( );

Example
class A extends Thread
{
Dept. of CS 3 JSSCW

public void run( )


{
for(int i=1;i<=5;i++)
{
[Link](“ from thread A: i=”+i)
}
[Link](“Exit thread A”);
}
}
class B extends Thread
{
public void run( )
{
for(int j=1;j<=5;j++)
{
[Link](“ from thread B: j=”+j)
}
[Link](“Exit thread B”);
}
}
class C extends Thread
{
public void run( )
{
for(int k=1;k<=5;k++)
{
[Link](“ from thread C: k=”+k)
}
[Link](“Exit thread C”);
}
}
Class mythread{
public static void main(String[ ] args){
A t1=new A( );
B t2=new B( );
Dept. of CS 4 JSSCW

C t3=new C( );
[Link]( );
[Link]( );
[Link]( );
Life cycle of a thread

During the life time of a thread, there are many states it can enter. They include:
1. Newborn state
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
A thread is always in one of these five states. It can move from one state to another via a
variety of ways as shown in the above figure.

1. Newborn State
When we create a thread object, the thread is born and is said to be in newborn state. The
thread is not yet scheduled for running. At this state, we can do only one of the following
with it:
 Schedule it for running using start() method.
Dept. of CS 5 JSSCW

 Kill it using stop() method


If scheduled, it moves to the runnable state. If we attempt
to use any other method at this stage, an exception will
be thrown.

2. Runnable state (start())

The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are
waiting for execution. If all threads have equal priority, then they are given time slots for
execution in round robin fashion. i.e. first-come, first-serve manner. The thread that
relinquishes control joins the queue at the end and again waits for its turn. This process of
assigning time to threads is known as time-slicing. If we want a thread to relinquish control to
another thread of equal priority before its turn comes, we can do so by using the yield()
method as shown in below figure.

3. Running State
Running means that the processor has given its time to the thread for its execution. The
thread runs until it relinquishes control on its own or it is preempted by a higher priority
thread. A running thread may relinquish its control in one of the following situations:
a. Suspend() and resume()Methods:-
This approach is useful when we want to suspend a thread for some time due to certain
reason, but do not want to kill it. A suspended thread can be revived by using the
resume() method.
Dept. of CS 6 JSSCW

b. Sleep() Method :-
This means that the thread is out of the queue during this time period. The thread re-
enter the runnable state as soon as this time period is elapsed.

c. Wait() and notify() methods :- blocked until certain condition occurs

4. Blocked State
A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state. This happens when the thread is suspended, sleeping, or
waiting in order to satisfy certain requirements. A blocked thread is considered “not
runnable” but not dead and therefore fully qualified to run again.
Blocking a Thread
A thread can also be temporarily suspended or blocked form entering into the runnable and
subsequently running state by using either of the following thread methods:
 Sleep() – blocked for a specified time.
 Suspend() – blocked until further orders.
 Wait() – blocked until certain condition occurs.
Dept. of CS 7 JSSCW

These methods cause the thread to go into the blocked state. The thread will return to the
runnable state when the specified time is elapsed in the case of sleep(), the resume() method
is invoked in the case of suspend(), and the notify() method is called in the case of wait().
5. Dead State
A running thread ends its life when is has completed executing its run() method. It is a natural
death. However, we can kill it by sending the stop message to it at any state thus causing a
premature death to it. A thread can be killed as soon it is born, or while it is running, or even
when it is in “not runnable” (blocked) condition.

Methods of Thread class

Method Description

Thread currentThread() returns a reference to the current thread


Void sleep(long msec) causes the current Throws thread to wait for
msec milliseconds
InterruptedException
Void sleep(long msec, int nsec) causes the current Throws to wait for msec
milliseconds plus nsec nanoseconds
InterruptedException
Void yield() causes the current thread to yield control of
the processo to other
String getName() Returns the name of the thread.
Int getPriority() Returns the priority of the thread
Boolean isAlive() Returns true if this thread has been started
and has not Yet died. Otherwise, returns
false.
Void run() Comprises the body of the thread. This
method is overridden by subclasses.
Void setName(String s) sets the name of this thread to s.
Void setPriority(int p) Sets the priority of this thread to p.
Void start() starts the thread

Thread Priority
In java, each thread is assigned a priority, which affects the order in which it is scheduled for
running. Java permits us to set the priority of a thread using the setPriority() method as
follows:
[Link](intNumber);
The intNumber may assume one of these constants or any value between 1 and 10.
Dept. of CS 8 JSSCW

The intNumber is an integer value to which the thread’s priority is set. The Thread class
defines several priority constants:
 MIN_PRIORITY=1
 NORM_PRIORITY=5
 MAX_PRIORITY=10
The default setting is NORM_PRIORITY.
Example Program
class A extends Thread
{
public void run()
{
[Link]("Thread A started");
for(int i=1;i<5;i++)

[Link](" thread A: i="+i);


[Link](" Exit from Thread A");
}
}
class B extends Thread
{
public void run()
{
[Link]("Thread B started");
for(int i=1;i<5;i++)
[Link](" thread B: i="+i);
[Link](" Exit from Thread B");
}
}
class C extends Thread
{
public void run()
{
[Link]("Thread C started");
for(int i=1;i<5;i++)
[Link](" thread C: i="+i);
[Link](" Exit from Thread C");
Dept. of CS 9 JSSCW

}
}
public class Threading {
public static void main(String[] args) {
A ta=new A();
B tb=new B();
C tc=new C();
[Link](Thread.MAX_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]("Start Thread A");
[Link]();
[Link](" Start Thread B");
[Link]();
[Link]("Start Thread C");
[Link]();
}
}

APPLET
An applet is a program that can be referenced by the html source code of web page. It is
dynamically downloaded from a Web Server to a browser. The applet then executes within
the environment provided by the browser. Alternatively you may use a tool such as the
appletviewer to run it.
It is important to recognize that downloading code from the Internet and executing it on your
computer is inherently dangerous. Therefore, applet do not have the same capabilities as Java
applications. They are restricted to operating within the confines of a “sandbox”. In other
words code that is “untrusted” is not allowed to operate outside certain boundaries.
For Example, applets are normally not allowed to read or write to your local disk. This would
obviously be risky because they could accidentally or maliciously destroy any data stored on
that device. Applet cannot execute any native code.
An applet may open a socket connection back to the host from which it was downloaded, but
not to any other host. The reason for this restriction can be understood if you imagine a
configuration in which a firewall protects a corporate Intranet from computer hackers.
Assume that an employee has downloaded an applet from internet to a PC or workstation. If
that applet is allowed to open sockets to any machine, it would then have the potential to steal
proprietary information and send back to the hacker’s machine. This must be prevented.
Therefore, an applet is not allowed to contact any of those private machines.

Difference between Applet and Application


Dept. of CS 10 JSSCW

Applet are not full-featured application programs. They are usually written to accomplish a
small task or a component of a task. Since they are usually designed for use on the Internet,
they impose certain limitations and restrictions in their design.
 Applet do not use main() method for initiating the execution of the code. Applets,
when loaded, automatically call certain methods of Applet class to start and execute
the applet code.
 Unlike stand-alone applications, applet cannot be run independently. They are run
from inside a web page using a special feature known as HTML tag.
 Applets cannot read from or write to the files in the local computer.
 Applet cannot communicate with other servers on the network.
 Applets cannot run any program the local computer.
Building Applet Code
It is essential that our applet code uses the services of two classes, namely, Applet and
Graphics from the Java Class Library. The Applet class which is contained in the
[Link] package provides life and behavior to the applet through its methods such as
init(),start() and paint() . Unlike with applications, where Java calls main() method directly
to initiate the execution of the program, when an applet is loaded, Java automatically calls a
series of Applet class methods for starting, running, and stopping the applet code. The applet
class therefore maintains the lifecycle of an applet.
The paint() method of the Applet class, when it is called, actually displays the result of the
applet code on the screen. The output may be text, graphics, or sound. The paint() method,
which requires a Graphics object as an argument, is defined as follows :
public void paint(Graphics g)
This requires that the applet code imports [Link] package that contains the Graphics class.
All output operations of an applet are performed using the methods defined in the Graphics
class.
import java,awt.*;
import [Link].*;
public class appletclassname extends Applet {
public void paint(Graphics g) {
[Link](“Hello Java”,10,100);
}
}
Applet Life Cycle
Every Java applet inherits a set of default behaviors from the applet class. The applet state
include:
1. Born or Initialization state 2. Idle State
3. Running state 4. Dead or Destroyed State
Dept. of CS 11 JSSCW

Initialization State: Applet enters the initialization state when it is first loaded. This is
achieved by calling the init() method of Applet Class. The applet is born. We required
following at this stage:
 Create objects needed by the applet.
 Set up initial values
 Load images or fonts
 Set up colors
The initialization occurs only once in the applet’s life cycle. To provide any of the behavior
we must override the init() method.
public void init()
{
-----
}
Running State : Applet enters in the running state when the system calls the start() method
of Applet class. This occurs automatically after the applet is initialized. Starting can also
occur if the applet is already in “stopped”(idle) state. For example, we may leave the web
page containing the applet temporarily to another page and return back to the page. This
again starts applet running. Note that, unlike init() method, the start() method may be called
more than once. We may override the start() method to create a thread to control a thread to
control the applet.
Idle or Stopped State: An applet becomes idle when it is stopped from running. Stopping
occurs automatically when we leave the page containing the currently running applet. We can
also do so by calling the stop() method explicitly. If we use a thread to run the applet, then
we must use stop() method to terminate the thread. We can achieve by overriding the stop()
method.
Dead State : An applet is said to be dead when it is removed from memory. This occurs
automatically by invoking the destroy() method when we quit the browser. Like
Initialization, destroying stage occurs only once in the applets life cycle.
Dept. of CS 12 JSSCW

Display State: Applet moves to the display state whenever it has to perform some output
operations on the screen. This happens immediately after the applet enters into the running
state. The paint() method is called to accomplish this task.
The Graphics Class:
A Graphics object encapsulates a set of methods that can perform graphics output.
Specifically it allows you to draw lines, ovals, rectangles, strings, images, characters, and
arcs, some of the commonly used methods of the Graphics class are summarized below:
Method Description
void drawArc(int x,int y,int w,int h, int Draws an arc between degrees0 and degrees1. The
degrees0,int degrees1) center of the arc is the center of a rectangle with
upper-left corner at coordinates x and y, width w, and
height h. Zero degrees is at position 3pm on a watch.
The angle increases in a counter clockwise direction.
Void drawImage(Image img, int x,int Draws the image img so its upper-left corner is at x,y.
y,ImageObserver io)
void drawLine(int x0,int y0,int x1,. Draws a line between the points at x0,y0 and x1,y1
Int y1)
Void drawOval(int x,int y, int w,int h) Draws an oval.

void drawPolygon(int x[],int y[],int n) Draws a polygons with n corners.


Void drawRect(int x,int y,int w,int h) Draws a rectangle
Void drawString(String str,int x,int y) Draws str at location x,y
void fillarc(int x,int y,int w,int h, Fills an arc between degrees0 and degrees1.
Int degrees0,int degrees1)
void fillOval(int x,int y,int w,int h) Fills an Oval
void fillPolygon(int x[],int y[],int n) Fills the polygon with n corners.
Void fillRect(int x,int y,int w,int h) Fills a rectangle with upper-left corner at coordinates
x

Display Text : Normally drawString() method is used to draw string on the screen well
giving additional capabilities for controlling the appearance and placement of a string in an
applet. A font determines the size and appearance of characters in a string. That resides in
[Link].
The following is one constructs : Font(String name,int style,int ps)
Here name identifies the font like Arial. The style may be bold,italic or plain and the point
size of the font is ps.
To create a Font setFont() method of the Graphics class.
void setFont(Font font)
Dept. of CS 13 JSSCW

Here, font is a Font object. After this method is called, any strings that are output via the
drawString() method are displayed with that font. The [Link] class allows you
to get several metrics about the size of a font. In addition, you may also determine the size of
a string that displayed in that font. These quantities are provided in pixels.

You might also like