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

Threads and Applets

Uploaded by

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

Threads and Applets

Uploaded by

Satya Narayana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Multithreading

Multithreading is a conceptual programming concept where a program (process) is divided


into two or more subprograms (process), which can be implemented at the same time in
parallel. A multithreaded program contains two or more parts that can run concurrently. Each
part of such a program is called a thread, and each thread defines a separate path of execution.
A process consists of the memory space allocated by the operating system that can contain
one or more threads. A thread cannot exist on its own; it must be a part of a process.

There are two distinct types of Multitasking i.e. Processor-Based and Thread-Based
multitasking.

Q: What is the difference between thread-based and process-based multitasking?

Ans: As both are types of multitasking there is very basic difference between the two.
Process-Based multitasking is a feature that allows your computer to run two or more
programs concurrently. For example you can listen to music and at the same time chat with
your friends on Facebook using browser. In Thread-based multitasking, thread is the smallest
unit of code, which means a single program can perform two or more tasks simultaneously.
For example a text editor can print and at the same time you can edit text provided that those
two tasks are perform by separate threads.

Q: Why multitasking thread requires less overhead than multitasking processor?

Ans: A multitasking thread requires less overhead than multitasking processor because of the
following reasons:

 Processes are heavyweight tasks where threads are lightweight

 Processes require their own separate address space where threads share the address
space

 Interprocess communication is expensive and limited where Interthread


communication is inexpensive, and context switching from one thread to the next is
lower in cost.

Benefits of Multithreading

1. Enables programmers to do multiple things at one time

JAVA NOTES BY ACHIN JAIN 1


JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

2. Programmers can divide a long program into threads and execute them in parallel
which eventually increases the speed of the program execution

3. Improved performance and concurrency

4. Simultaneous access to multiple applications

Life Cycle of Thread

A thread can be in any of the five following states

1. Newborn State: When a thread object is created a new thread is born and said to be
in Newborn state.

2. Runnable State: If a thread is in this state it means that the thread is ready for
execution and waiting for the availability of the processor. If all threads in queue are of
same priority then they are given time slots for execution in round robin fashion

3. Running State: It means that the processor has given its time to the thread for
execution. A thread keeps running until the following conditions occurs

a. Thread give up its control on its own and it can happen in the following
situations

i. A thread gets suspended using suspend() method which can only be


revived with resume() method

ii. A thread is made to sleep for a specified period of time using


sleep(time) method, where time in milliseconds

iii. A thread is made to wait for some event to occur using wait () method.
In this case a thread can be scheduled to run again using notify ()
method.

b. A thread is pre-empted by a higher priority thread

4. Blocked State: If a thread is prevented from entering into runnable state and
subsequently running state, then a thread is said to be in Blocked state.

5. Dead State: A runnable thread enters the Dead or terminated state when it completes
its task or otherwise terminates.

JAVA NOTES BY ACHIN JAIN 2


JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Fig: Life Cycle of Thread

Main Thread

Every time a Java program starts up, one thread begins running which is called as the main
thread of the program because it is the one that is executed when your program begins.

 Child threads are produced from main thread

 Often it is the last thread to finish execution as it performs various shut down
operations

Creating a Thread

Java defines two ways in which this can be accomplished:

 You can implement the Runnable interface.


 You can extend the Thread class, itself.

Create Thread by Implementing Runnable

The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:

public void run( )

JAVA NOTES BY ACHIN JAIN 3


JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

You will define the code that constitutes the new thread inside run() method. It is important
to understand that run() can call other methods, use other classes, and declare variables, just
like the main thread can.

After you create a class that implements Runnable, you will instantiate an object of type
Thread from within that class. Thread defines several constructors. The one that we will use is
shown here:

Thread(Runnable threadOb, String threadName);

Here threadOb is an instance of a class that implements the Runnable interface and the name
of the new thread is specified by threadName. After the new thread is created, it will not start
running until you call its start( ) method, which is declared within Thread. The start( )
method is shown here:

void start( );

Example to Create a Thread using Runnable Interface

Output:

Create Thread by Extending Thread

The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class. The extending class must override the run( ) method,

JAVA NOTES BY ACHIN JAIN 4


JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

which is the entry point for the new thread. It must also call start( ) to begin execution of the
new thread.

Example to Create a Thread by Extending Thread Class

Output:

Thread Methods

SN Methods with Description


1 public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this
Thread object.
2 public void run()
If this Thread object was instantiated using a separate Runnable target, the run()
method is invoked on that Runnable object.
3 public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for
retrieving the name.
4 public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5 public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6 public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread

JAVA NOTES BY ACHIN JAIN 5


JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

to block until the second thread terminates or the specified number of milliseconds
passes.
7 public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8 public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started
but before it runs to completion.

Q: Can we start a thread twice?

Ans: No, if a thread is started it can never be started again, if you do so, an
illegalThreadStateException is thrown. Example is shown below in which a same thread is
coded to start again

As you can see two statements to start


a same thread is written in the code
which will not give error during
compilation but when you run it you
can see an Exception as shown in the
Output Screenshot.

Output:

Use of Yield() Method

Causes the currently running thread to yield to any other threads of the same priority that are
waiting to be scheduled

JAVA NOTES BY ACHIN JAIN 6


JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Example

Condition is checked and when i==2


yield() method is evoked taking
control to thread B

As you can see in the output below, thread A gets started and when condition if(i==2)
gets satisfied yield() method gets evoked and the control is relinquished from thread
A to thread B which run to its completion and only after that thread a regain the control
back.

JAVA NOTES BY ACHIN JAIN 7


JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Output

Use of stop() Method


The stop() method kills the thread on execution

Example

Condition is checked and when i==2


stop() method is evoked causing
termination of thread execution

Output

Use of sleep() Method


Causes the currently running thread to block for at least the specified number of milliseconds.
You need to handle exception while using sleep() method.

JAVA NOTES BY ACHIN JAIN 8


JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Example

Condition is checked and when i==2


sleep() method is evoked which halts
the execution of the thread for 1000
milliseconds. When you see output
there is no change but there is delay in
execution.

Output

Use of suspend() and resume() method


A suspended thread can be revived by using the resume() method. 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.

Following is the example in which two threads C and A are created. Thread C is started ahead
of Thread A, but C is suspended using suspend() method causing Thread A to get hold of the
processor allowing it to run and when Thread C is resumed using resume() method it runs to
its completion.

JAVA NOTES BY ACHIN JAIN 9


JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Example

Although Thread ‘C’ is started earlier


than Thread ‘A’ but due to suspend
method Thread ‘A’ gets completed
ahead of Thread ‘C’

Output

1
JAVA NOTES BY ACHIN JAIN
0
JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Thread Priority

Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.

Java 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 very much platform dependent.

Example

In the above code, you can see Priorities of Thread is set to maximum for Thread A which lets
it to run to completion ahead of C which is set to minimum priority.

Output:

1
JAVA NOTES BY ACHIN JAIN
1
JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Use of isAlive() and join() method

The java.lang.Thread.isAlive() method tests if this thread is alive. A thread is alive if it has been
started and has not yet died. Following is the declaration for java.lang.Thread.isAlive() method

public final boolean isAlive()

This method returns true if this thread is alive, false otherwise.

join() method waits for a thread to die. It causes the currently thread to stop executing until
the thread it joins with completes its task.

Example

At this point Thread A is


alive so the value gets
printed by isAlive()
method is “true”

join() method is called


from Thread A which
stops executing of further
statement until A is Dead

Now isAlive() method


returns the value false as
Output the Thread A is complete

1
JAVA NOTES BY ACHIN JAIN
2
JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Synchronization

When two or more threads need access to a shared resource, they need some way to ensure
that the resource will be used by only one thread at a time. The process by which this
synchronization is achieved is called thread synchronization. The synchronized keyword in
Java creates a block of code referred to as a critical section. Every Java object with a critical
section of code gets a lock associated with the object. To enter a critical section, a thread needs
to obtain the corresponding object's lock.

synchronized(object)
{
// statements to be synchronized
}
Problem without using Synchronization

In the following example method updatesum() is not synchronized and access by both the
threads simultaneously which results in inconsistent output. Making a method synchronized,
Java creates a “monitor” and hands it over to the thread that calls the method first time. As
long as the thread holds the monitor, no other thread can enter the synchronized section of
the code. Writing the method as synchronized will make one thread enter the method and till
execution is not complete no other thread can get access to the method.

1
JAVA NOTES BY ACHIN JAIN
3
JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Output when
method is declared
as synchronized

Output

1
JAVA NOTES BY ACHIN JAIN
4
JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Interthread Communication

It is all about making synchronized threads communicate with each other. It is a mechanism
in which a thread is paused running in its critical section and another thread is allowed to
enter in the same critical section to be executed. It is implemented by the following methods
of Object Class:

 wait( ): This method tells the calling thread to give up the monitor and go to sleep
until some other thread enters the same monitor and calls notify( ).
 notify( ): This method wakes up the first thread that called wait( ) on the same object.
 notifyAll( ): This method wakes up all the threads that called wait( ) on the same
object. The highest priority thread will run first.

These methods are implemented as final methods in Object, so all classes have them. All three
methods can be called only from within a synchronized context.

Example

If both these methods are commented


which means there is no communication,
output will be inconsistent. See Output 2

1
JAVA NOTES BY ACHIN JAIN
5
JAVA NOTES – ACHIN JAIN - ASSISTANT PROFESSOR, CSE(NIEC)

Output 1:

Output 2:

1
JAVA NOTES BY ACHIN JAIN
6
The threads are acting on background is called Daemon threads.The main
objective is to provide support for non daemon threads.(Main thread).For
example if main thread runs with low memory then JVM runs garbage
collector(go) to destroy useless objects. So that no.of bytes of free memory
will be improved. With this free memory main thread can continue its
execution. These daemon threads runs with low priority but based on our

requirement daemon threads can run with high priority also.

1.public void setDaemon(boolean b)

2.public boolean isDaemon()

we can check daemon nature of a thread by using isDaemon() method

of Thread class.

we can change daemon nature of a thread by using setDaemon() method.

But changing daemon nature is possible before starting of a thread only.


After starting of a thread if you are trying to change daemon nature then we
will get run time exception saying IllegalThreadStateException.

The default nature of a thread main thread is always non –daemon. All
remaining threads daemon nature is inherited from parent to child. i.e if the
parent thread is Daemon then automatically childthread is also daemon and
if the parent thread is non –daemon then automatically child thread is also
non –daemon.

Note:- It is impossible to change daemon nature of main thread because it is


already started by at begining.
class Thread1 extends Thread
{
public void run()
{
for(int i=1;i<=10;i++){
System.out.println("CHILD TREAD");
try{Thread.sleep(2000);}
catch(Throwable t){}
}
public static void main(String[] args)
{
Thread1 t1=new Thread1();
t1.setDaemon(true);
t1.start();
System.out.println("END OF MAIN:");
}
}
ThreadGroup in Java
A ThreadGroup in Java represents a group of threads or thread
groups and belongs to the java.lang.ThreadGroup class. The main
advantage of a thread group is that we can perform operations like
suspend, resume, or interrupt for all threads using a single
function call. Every thread in a thread group has a parent thread
except the initial thread and hence it represents a tree structure. It
can access all the information about its own thread group.
ThreadGroup class is very useful when we want to perform the
same operation on multiple threads.

Constructor Description

ThreadGroup(String name) Creates a thread group with the specified


name

ThreadGroup(ThreadGroup parent, Creates a thread group with the specified


String name) thread group parent and name
Methods of ThreadGroup
The ThreadGroup class in Java has the below methods to perform various
operations.

Method Description

int activeCount() Returns the number of active threads in the Thread


group

int activeGroupCount() Returns the number of active threads groups in the


specified group

void checkAccess() Checks if the current thread has permission to


modify the groups access

void destroy() Destroys the thread group

int getMaximumPriority() Returns the maximum priority of the thread group

String getName() Returns the name of the thread group

ThreadGroup getParent() Returns the parent of the thread group

boolean isDestroyed() Checks if the thread group is destroyed

void list() Prints information about the thread group to the


standard output stream

boolean Checks if the thread group is the specified thread


parentOf(ThreadGroup tg) group argument or its ancestor thread groups

void setMaxPriority(int p) Sets the specified maximum priority for the thread
group
APPLETS
Q. What are the differences between Applets and Standalone application
program?
Although both the Applets and standalone application are java programs,
these are not full feature application programs. It is designed for Internet. There
are certain limitations and restrictions in their design.
 Applets don't use the main method for initiating the execution of the code.
Applets when loaded automatically called certain methods of the Applet
class to start and execute the code.
 Applet cannot run independently but they run from inside a webpage
using HTML Tags.
 Applets cannot read from or write to the files in the local computer.
 Applets cannot communicate with other servers on the network.
 Applet cannot run program from the local computer.
Q. Explain Applet lifecycle?
Every java Applet inherits a set of default behaviors from the applet class.
As a result when an Applet is loaded it undergoes a series of changes in its state
as shown in the figure below.
Initialization State:
Applet enters the initialization state when it is first loaded. This is
achieved by calling init() method of Applet class. The Applet is born at this
stage. we must do the following steps:
1. create objects needed by Applet
2. Setup initial values
3. load images or font
4. setup colors

Begin Initialization
Begin
(Load Applet)

Start ()
Stop ()

Running Idle Stopped


Display Start ()

Paint () Destroy ()

Destroyed Dead End


106 | P a g
e
Initialization State:
The initialization occurs only once in the applets life cycle to provide any of
the behavior as mentioned above. We must override the init() method
public void init()
{
........
........(action)
}
Running State:
Applet enters 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 stopped (idle) state. For ex:-we may leave
the webpage containing the applet temporarily to another page and return back
to this page. This again starts the 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 the applet.
public void start()
{
.........
.........(action)
}
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 to terminate the Thread we can
achieve this by overriding the stop() method.
public void stop()
{
........
........(action)
}
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 browsers like
initialization destroying stage occurs only once in the applets lifecycle if the
applet has created any resources, like threads. We may override the
destroy()method to clean up these resources
public void destroy()
{
.......
.......(Action)
}
Display State:
Applet moves to the display state whenever it has to perform some output
operation on the screen.This happens immediately after the applet enters into
the running state.The paint()method is called to accomplish this task.Almost
every applet will have a paint() method like other method in the life cycle.The
default version of paint() method does absolutely nothing we must therefore 107 | P a g
override this method if we went anything to be displayed on the screen. e
public void paint(Graphics g)
{
.......
.......(Display Statements)
}
It is to be noted that the display state is not considered as a part of the
applets lifecycle. In fact the paint() method is defined in the applet class. It is
inherited from the component class, a super class of applet.
//Write a simple java applet program
import java.awt.*;
import java.applet.*;
public class Myapp extends Applet
{
public void init()
{
setBackground(Color.yellow);
}
public void paint(Graphics g)
{
g.drawString("baba is great",50,100);
}
}
Compile the java program:
<html>
<applet code="Myapp.class"height=300 Width=500>
</applet>
</html>
Q. What are the steps involved in developing, testing in applets?
1. Building an applet code
2. Creating an execute applet(class file)
3. designing a web using HTML tags
4. preparing an applet tags
5. Incorporating applet tag into the web page
6. Creating HTML file
7. Testing the applet code with the applet viewed(file name,HTML)
Animations in Applet:
Image img=getImage(SetDocumentBase(),"a.gif");
Here image class belongs to java.awt package and getImage method
belongs to applet class. get document Base() is a method of an applet class that
gives directory path. Where the image is located.
g.drawImage(img,x,y,obj);
x and y represents the coordinates starting from where the image should be
displayed.obj represents image observer which stores into the memory. Since
this is not needed we can pass in its place.
//program
import java.awt.*;
import java.applet.*;
public class Animate extends Applet 108 | P a g
{ e
public void paint(Graphics g)
{
Image img=getImage(getDocumentBase(),"a.gif");
for(int x=0;x<800;x++)
{
g.drawImage(img,x,0,null);
try
{
Thread.sleep(20);
}
catch(InterruptedException e){}
}
}
}

compile: javac Animate.java


<html>
<applet code="Animate class"height=300,width=500>
</applet>
</html>
appletviewer Animate html
Q. What are the uses of applets?
1. Applets can be used for multiple purpose.
2. Applets are used on internet for creating a dynamic web pages.(These are
of two types of webpages one is static and dynamic)User cannot interact
with the page dynamic.
3. Applets are used for creating animations and games.
Q. What are Applet parameters?
Applet tag can be used param tag to pass information’s to applet to
recieve the values of the parameters. An applet uses get parameters.
Ex:
import java.applet.*;
import java.awt.*;
public class Tax extends Applets
{
String name,str;
float sal,tax;
public void init()
{
name=getParameter("t1");
str=getParameter("t2");
sal=Float.parseFloat(str);
cal(sal);
}
public void cal(float sal)
{
if(sal<=1000000)
tax=0.0f;
else 109 | P a g
if(sal<=200000) e
tax=sal*0.1f;
else
tax=sal*0.2f;
}
public void paint(Graphics g)
{
g.drawString("Hello"+name,20,100);
g.drawString("your salary:"+sal,20,120);
g.drawString("pay the Tax:"+tax,20,140);
}
}
compile: javac Tax.java
<html>
<applet code="Tax.class"height=300,width=200>
<param name ="t1"value="kumar">
<param name ="t2"value="15000">
</applet>
</html>
Q. What is Abstract Window tool kit?
It represents a class library to develop applications using graphical user
interface. The java.awt package got a classes and interface to develop GUI and
let the user interact in a more friendly way with the application.
//Write a program to create a frame by creating an object to Frame class
import java.awt.*;
class MyFrame
{
public static void main(String args[])
{
Frame f=new Frame("My AWT Frame");
f.setSize(300,500);
f.setVisible(true);
}
}
//Write a program to create a frame by creating an object to subclass of
Frame class
import java.awt.*;
class MyFrame2 extends Frame
{
MyFrame2(String str)
{
super(str);
}
public static void main(String args[])
{
MyFrame2 f=new MyFrame2("My AWT Frame");
f.setSize(300,250);
f.setVisible(true);
}
} 110 | P a g
e

You might also like