Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Multi Threaded Programming and Event

Handling
4.1. Multi Threaded Programming
4.1.1 What are threads

Life Cycle of a Thread

Following are the stages of the life cycle −

 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.

Java thread priorities are in the range between MIN_PRIORITY (a constant


of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is
given priority NORM_PRIORITY (a constant of 5).

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.

Create a Thread by Implementing a Runnable


Interface
If your class is intended to be executed as a thread then you can achieve
this by implementing a Runnable interface. You will need to follow three
basic steps −

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);

Where, threadObj is an instance of a class that implements


the Runnableinterface and threadName is the name given to the new
thread.
Step 3
Once a 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();

Create a Thread by Extending a Thread Class


The second way to create a thread is to create a new class that
extends Thread 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
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.

Threads can be created by using two mechanisms :


1. Extending the Thread class
2. Implementing the Runnable Interface

Thread creation by extending the Thread class


We create a class that extends the java.lang.Thread class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object of
our new class and call start() method to start the execution of a thread. Start() invokes the run()
method on the Thread object.

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.

Thread Class vs Runnable Interface

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.

Why use Synchronization


The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Java synchronized method


If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any 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.

Java synchronized method


If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any 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.

1. //Program of synchronized method by using annonymous class


2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. public class TestSynchronization3{
15. public static void main(String args[]){
16. final Table obj = new Table();//only one object
17.
18. Thread t1=new Thread(){
19. public void run(){
20. obj.printTable(5);
21. }
22. };
23. Thread t2=new Thread(){
24. public void run(){
25. obj.printTable(100);
26. }
27. };
28.
29. t1.start();
30. t2.start();
31. }
32. }

Synchronized block in java


Synchronized block can be used to perform synchronization on any specific resource of the
method.

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.

Points to remember for Synchronized block

o Synchronized block is used to lock an object for any shared resource.


o Scope of synchronized block is smaller than the method.

Syntax to use synchronized block


synchronized (object reference expression) {
//code block
}

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
}

public class TestSynchronizedBlock2{


public static void main(String args[]){
final Table obj = new Table();//only one object

Thread t1=new Thread(){


public void run(){
obj.printTable(5);
}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
};

t1.start();
t2.start();
}
}

Producer Consumer Problem


Producer-Consumer solution using threads in Java
In computing, the producer–consumer problem (also known as the bounded-buffer problem)
is a classic example of a multi-process synchronization problem. The problem describes two
processes, the producer and the consumer, which share a common, fixed-size buffer used
as a queue.
 The producer’s job is to generate data, put it into the buffer, and start again.
 At the same time, the consumer is consuming the data (i.e. removing it from the buffer),
one piece at a time.
Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the
consumer won’t try to remove data from an empty buffer.
Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the
consumer removes an item from the buffer, it notifies the producer, who starts to fill the
buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be
empty. The next time the producer puts data into the buffer, it wakes up the sleeping
consumer.
An inadequate solution could result in a deadlock where both processes are waiting to be
awakened.
class PC
{
int a[]=new int[4];
int capacity = 2;
int size=0;
public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
synchronized (this)
{
while (size==capacity)
wait();

System.out.println("Producer produced-"+value);
a[size++]=value++;
notify();
Thread.sleep(1000);
}
}
}

// Function called by consumer thread


public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{
while (size==0)
wait();
int val = a[size--];
System.out.println("Consumer consumed-"+val);
notify();
Thread.sleep(1000);
}
}
}
}

public class Main


{
public static void main(String[] args)

{
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()

Life cycle of an applet :

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>*/

public class AppletDemo extends Applet


{

public void paint(Graphics g)


{
g.drawString("Hello World", 20, 20);
}

Delegation Event Model:

addTypeListener(TypeListener e)

import java.awt.event.*;
import java.applet.*;
import java.awt.Graphics;

/*<applet code="MyMouseEvent.class" width=300 height=100></applet>*/

public class MyMouseEvent extends Applet implements MouseListener


{
String msg="";
int mx=0,my=0;
public void init()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
mx=0;
my=10;
msg="mouse clicked";
repaint();
}

public void mouseEntered(MouseEvent e)


{
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void paint(Graphics g)
{
g.drawString(msg,mx,my);
}
}

import java.awt.event.*;
import java.applet.*;
import java.awt.Graphics;

/*<applet code="AdapterDemo.class" width=300 height=100></applet>*/

class MyMouseAdapter extends MouseAdapter


{
AdapterDemo d;
public MyMouseAdapter(AdapterDemo d)
{
this.d=d;
}
public void mouseClicked(MouseEvent e)
{
d.showStatus("MouseCLicked");
}
}

public class AdapterDemo extends Applet


{
public void init()
{
addMouseListener(new MyMouseAdapter(this));
}
}

You might also like