Ooc Module 4
Ooc Module 4
Handling
4.1. Multi Threaded Programming
4.1.1 What are threads
New − A new thread begins its life cycle in the new state. It remains in this
state until the program starts the thread. It is also referred to as a born
thread.
Runnable − After a newly born thread is started, the thread becomes runnable.
A thread in this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. A thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
Thread Priorities
Every Java thread has a priority that helps the operating system determine
the order in which threads are scheduled.
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread
priorities cannot guarantee the order in which threads execute and are very
much platform dependent.
Step 1
As a first step, you need to implement a run() method provided by
a Runnable interface. 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 the run() method −
public void run( )
Step 2
As a second step, you will instantiate a Thread object using the following
constructor −
Thread(Runnable threadObj, String threadName);
Step 1
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 2
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 −
void start( );
Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
G
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method. Then
we instantiate a Thread object and call start() method on this object.
1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t
support multiple inheritance. But, if we implement the Runnable interface, our class can still
extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it provides
some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you
can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
class Table{
void printTable(int n)
{
synchronized(this)
{//synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
Try
{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
t1.start();
t2.start();
}
}
System.out.println("Producer produced-"+value);
a[size++]=value++;
notify();
Thread.sleep(1000);
}
}
}
{
PC pc = new PC();
Thread t1 = new Thread()
{
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
} };
Thread t2 = new Thread()
{
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
} };
t1.start();
t2.start();
try{
t1.join();
}
catch(Exception e)
{
System.out.println(e);
}
try{
t2.join();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Java Applet Basics
Applet is a Java program that can be embedded into a web page. It runs inside the web browser
and works at client side. Applet is embedded in a HTML page using the APPLET or OBJECT
tag and hosted on a web server.
Applets are used to make the web site more dynamic and entertaining.
1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
2. Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer. JDK provides a standard applet viewer tool called applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather it is handled
with various AWT methods, such as drawString()
It is important to understand the order in which the various methods shown in the above image
are called. When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
Let’s look more closely at these methods.
1. init( ) : The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet after
it has been stopped. Note that init( ) is called once i.e. when the first time an applet is
loaded whereas start( ) is called each time an applet’s HTML document is displayed
onscreen. So, if a user leaves a web page and comes back, the applet resumes execution
at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be
redrawn. This situation can occur for several reasons. For example, the window in which
the applet is running may be overwritten by another window and then uncovered. Or the
applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the
applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain the
graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required.
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page, for example. When stop( ) is called,
the applet is probably running. You should use stop( ) to suspend threads that don’t need to
run when the applet is not visible. You can restart them when start( ) is called if the user
returns to the page.
5. destroy( ) : The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using. The stop( ) method is always called before destroy( ).
Creating Hello World applet :
Let’s begin with the HelloWorld applet :
import java.applet.Applet;
import java.awt.Graphics;
/* <applet code="HelloWorld" width=200 height=60>
</applet>*/
addTypeListener(TypeListener e)
import java.awt.event.*;
import java.applet.*;
import java.awt.Graphics;
import java.awt.event.*;
import java.applet.*;
import java.awt.Graphics;