Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Java Unit 4

Uploaded by

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

Java Unit 4

Uploaded by

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

Multithreading in Java

It is a process of executing multiple threads simultaneously.


A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
we use multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching between
the threads takes less time than process.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs
in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


 Each process has an address in memory. In other words, each process allocates a
separate memory area.
 A process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread in java


1. Before introducing the thread concept, we were unable to run more than one
task in parallel.
2. It was a drawback, and to remove that drawback, Thread Concept was
introduced.
3. A thread is a lightweight subprocess, the smallest unit of processing.
4. It is a separate path of execution.
5. Threads are independent.
6. If there occurs exception in one thread, it doesn't affect other threads.
7. It uses a shared memory area.
8. A Thread allows a program to operate more efficiently by running multiple tasks
simultaneously.
9. In order to perform complicated tasks in the background, we used the Thread
concept in Java.
10. All the tasks are executed without affecting the main program.
11. In a program or process, all the threads have their own separate path for
execution, so each thread of a process is independent.

As shown in the above figure, a thread is executed inside the process. There is
context-switching between the threads. There can be multiple processes inside
the OS, and one process can have multiple threads.
Note: At a time one thread is executed only.

Thread Class
Java provides Thread class to achieve thread programming.
A Thread class has several methods and constructors which allow us to perform
various operations on a thread. The Thread class extends the Object class.
The Object class implements the Runnable interface. The thread class has the
following constructors that are used to perform various operations.
Methods of Thread Class

In java.lang.Thread class, several constructors have been declared for different purposes.
Some of them are:
 Thread(): no-argument constructor.
 Thread (String name): takes a string as an argument.
 Thread(Runnable r): takes reference (r) of a Runnable object as an argument.
 Thread(*Runnable r, String r): takes reference (r) of a Runnable object as well as a
string as arguments.

some of the most commonly used methods of the Thread class.


Method Name Usage
public void run() used to act as a thread.
public void start() used to start execution for a thread.
public void sleep(long used to temporarily terminate the invoking thread's execution
milliseconds) for a specified duration of time.
public void join() used to wait for a thread to die.
public void join(long used to wait for a thread to die for a specified duration of
milliseconds) time.
public int getPriority() used to get the priority of the thread.
public int setPriority(int
used to set or change the priority of the thread.
priority)
public String getName() used to get the name of the thread.
public void setName(String
used to set or change the name of the thread.
name)
public Thread
used to get the reference of currently executing thread.
currentThread()
public int getId() used to get the id of the thread.
public Thread.
used to get the state of the thread.
State.getState()
public boolean isAlive() used to check if the thread is alive or not.
used to temporarily pause the currently executing thread and
public void yield()
allow other threads to execute.
public void stop() used to check if the thread is a daemon thread.
public boolean isDaemon() used to mark the thread as daemon thread.
public void
used to mark the thread as daemon or user thread.
setDaemon(boolean b)
public void interrupt() used to make interrupts to the thread.
public boolean
used to check if the current thread has been interrupted or not.
isInterrupted()
public static boolean
used to check if the current thread has been interrupted or not.
interrupted()

Note: We have two more methods of the Thread class but they are now deprecated.
1. public void suspend(): which is used to suspend the current thread.
2. public void resume(): which is used to resume the currently suspended thread.
Creating Thread
A thread is created either by "creating or implementing" the Runnable Interface or by
extending the Thread class.
These are the only two ways through which we can create a thread.
Runnable Interface(run() method)
The Runnable interface is required to be implemented by that class whose instances
are intended to be executed by a thread. The runnable interface gives us
the run() method to perform an action for the thread.
start() method
The method is used for starting a thread that we have newly created. It starts a new
thread with a new callstack. After executing the start() method, the thread changes
the state from New to Runnable. It executes the run() method when the thread gets
the correct time to execute it.

Running Threads
We can use the Runnable interface or Thread class method use for the Implementation of
thread in java.
a. Using the Thread Class Method for the Implementation:

class ChildClass1 extends Thread {


// overriding the run() method
public void run() {
System.out.println("Run method of the first class.");
}
}
class ChildClass2 extends Thread {
// overriding the run() method
public void run() {
System.out.println("Run method of the second class.");
}
}

class ChildClass3 extends Thread {


// overriding the run() method
public void run() {
System.out.println("Run method of the third class.");
}
}

public class Test {


public static void main(String args[]) {
// creating object of the sub classes.
ChildClass1 cc1 = new ChildClass1();
ChildClass2 cc2 = new ChildClass2();
ChildClass3 cc3 = new ChildClass3();

// starting the new thread execution.


cc3.start();
cc2.start();
cc1.start();
}
}
Output:

The run method of the second class.


The run method of the third class.
The run method of the first class.

b. Using the Runnable Interface Implementation Method:

class ImplementingClass1 implements Runnable {


// overriding the run() method
public void run() {
System.out.println("Run method of the first implementing class.");
}
}

class ImplementingClass2 implements Runnable {


// overriding the run() method
public void run() {
System.out.println("Run method of the second implementing class.");
}
}

public class Test {


public static void main(String args[]) {
// creating object of the implementing class.
ImplementingClass1 ic1 = new ImplementingClass1();
ImplementingClass2 ic2 = new ImplementingClass2();

// passing the reference to the Thread class constructor.


Thread t1 = new Thread(ic1);
Thread t2 = new Thread(ic2);

// starting the new thread execution.


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

Output:

The run method of the first implementing class.


The run method of the second implementing class.

Life Cycle of Thread in Java


It is basically state transitions of a thread that starts from its birth and ends on its death.
When an instance of a thread is created and is executed by calling start() method of Thread
class, the thread goes into runnable state.
When sleep() or wait() method is called by Thread class, the thread enters into non-runnable
state.
From non-runnable state, thread comes back to runnable state and continues execution of
statements.
When the thread comes out of run() method, it dies. These state transitions of a thread are
called Thread life cycle in Java.
To work with threads in a program, it is important to identify thread state.

How to identify thread states in Java thread life cycle.


Thread States in Java
A thread is a path of execution in a program that enters any one of the
following five states during its life cycle. The five states are as follows:
1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead

1. New (Newborn State): When we create a thread object using Thread


class, thread is born and is known to be in Newborn state.
That is, when a thread is born, it enters into new state but the start()
method has not been called yet on the instance.
In other words, Thread object exists but it cannot execute any statement
because it is not an execution of thread.
Only start() method can be called on a new thread; otherwise,
an IllegalThreadStateException will be thrown.
2. Runnable state: Runnable state means a thread is ready for execution.
When the start() method is called on a new thread, thread enters into a
runnable state.
In runnable state, thread is ready for execution and is waiting for availability
of the processor (CPU time). That is, thread has joined queue (line) of
threads that are waiting for execution.
If all threads have equal priority, CPU allocates time slots for thread
execution on the basis of first-come, first-serve manner. The process of
allocating time to threads is known as time slicing. A thread can come into
runnable state from running, waiting, or new states.

3. Running state: Running means Processor (CPU) has allocated time slot
to thread for its execution.
When thread scheduler selects a thread from the runnable state for
execution, it goes into running state. Look at the above figure.
In running state, processor gives its time to the thread for execution and
executes its run method.
This is the state where thread performs its actual functions. A thread can
come into running state only from runnable state.
A running thread may give up its control in any one of the following
situations and can enter into the blocked state.
a) When sleep() method is invoked on a thread to sleep for specified time
period, the thread is out of queue during this time period.
The thread again reenters into the runnable state as soon as this time
period is elapsed.
b) When a thread is suspended using suspend() method for some time in
order to satisfy some conditions.
A suspended thread can be revived by using resume() method.
c) When wait() method is called on a thread to wait for some time.
The thread in wait state can be run again using notify() or notifyAll()
method.

4. Blocked state: A thread is considered to be in the blocked state when it


is suspended, sleeping, or waiting for some time in order to satisfy some
condition.

5. Dead state: A thread dies or moves into dead state automatically when
its run() method completes the execution of statements.
That is, a thread is terminated or dead when a thread comes out of run()
method. A thread can also be dead when the stop() method is called.
During the life cycle of thread in Java, a thread moves from one state to
another state in a variety of ways.
This is because in multithreading environment, when multiple threads are
executing, only one thread can use CPU at a time.
All other threads live in some other states, either waiting for their turn on
CPU or waiting for satisfying some conditions.
Therefore, a thread is always in any of the five states.
Lab program 17:-Create three threads
import java.lang.Thread;
import java.io.*;
class A extends Thread
{
Public void run()
{
try
{
for (int i = 1; i <= 5; i++)
{ sleep(1000); // The main thread sleeps for the 1000 milliseconds, which is 1 sec
// whenever the loop runs displaying the value of the variable
System.out.println(“GOOD MORNING”);
}
}
catch(InterruptException e)
{
System.out.println(“Thread interrupted”);
}
System.out.println(“Exit From Thread A”);
}
}
class B extends Thread
{
Public void run()
{
try
{
for (int j = 1; j <= 5; j++)
{ sleep(2000);
System.out.println(“HELLO”);
}
}
catch(InterruptException e)
{
System.out.println(“Thread interrupted”);
}
System.out.println(“Exit From Thread B”);
}}
class C extends Thread
{
Public void run()
{
try{
for (int k = 1; k<= 5; k++)
{ sleep(3000);
System.out.println(“WELCOME”);
}
}
catch(InterruptException e)
{
System.out.println(“Thread interrupted”);
}
System.out.println(“Exit From Thread C”);
}}
public class ThreadMethods
{
// main method
public static void main(String args[])
{
A threadA =new A();
B theadB=new B();
C threadC=new C();
System.out.println(“Start Thread A”);
threadA.start();
System.out.println(“Start Thread B”);
threadB.start();
System.out.println(“Start Thread C”);
threadC.start();
System.out.println(“End of main Thread”);
}
}

Deadlock in Java
Deadlock in Java is a part of multithreading.
Deadlock can occur in a situation when a thread is waiting for an object lock, that is
acquired by another thread and second thread is waiting for an object lock that is
acquired by first thread.
Since, both threads are waiting for each other to release the lock, the condition is
called deadlock.

Example of Deadlock in Java


TestDeadlockExample1.java
public class TestDeadlockExample1 {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};

t1.start();
t2.start();
}
}
Output:
Thread 1: locked resource 1
Thread 2: locked resource 2

How to Avoid Deadlock in Java?


Deadlocks cannot be completely resolved. But we can avoid them by following basic
rules mentioned below:
1. Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the
main reason for a deadlock condition. It normally happens when you give locks to
multiple threads.
2. Avoid Unnecessary Locks: The locks should be given to the important threads.
Giving locks to the unnecessary threads that cause the deadlock condition.
3. Using Thread Join: A deadlock usually happens when one thread is waiting for the
other to finish. In this case, we can use join with a maximum time that a thread
will take.
ThreadGroup in Java
 Java provides a convenient way to group multiple threads in a single object.
In such a way, we can suspend, resume or interrupt a group of threads by
a single method call.
 Java thread group is implemented by java.lang.ThreadGroup class.
 A ThreadGroup represents a set of threads.
 A thread group can also include the other thread group.
 The thread group creates a tree in which every thread group except the initial
thread group has a parent.
 A thread is allowed to access information about its own thread group, but
it cannot access the information about its thread group's parent thread group or
any other thread groups.

Constructors of ThreadGroup class


There are only two constructors of ThreadGroup class.

No. Constructor Description

1) ThreadGroup(String name) creates a thread group with given name.

2) ThreadGroup(ThreadGroup parent, creates a thread group with a given


String name) parent group and name.

Methods of ThreadGroup class


There are many methods in ThreadGroup class. A list of ThreadGroup methods is
given below.

S.N. Modifier Method Description


and Type

1) void checkAccess() This method determines if the


currently running thread has
permission to modify the thread
group.

2) int activeCount() This method returns an estimate of


the number of active threads in the
thread group and its subgroups.
3) int activeGroupCount() This method returns an estimate of
the number of active groups in the
thread group and its subgroups.

4) void destroy() This method destroys the thread


group and all of its subgroups.

5) int enumerate(Thread[] list) This method copies into the specified


array every active thread in the
thread group and its subgroups.

6) int getMaxPriority() This method returns the maximum


priority of the thread group.

7) String getName() This method returns the name of the


thread group.

8) ThreadGroup getParent() This method returns the parent of the


thread group.

9) void interrupt() This method interrupts all threads in


the thread group.

10) boolean isDaemon() This method tests if the thread group


is a daemon thread group.

11) void setDaemon(boolean This method changes the daemon


daemon) status of the thread group.

12) boolean isDestroyed() This method tests if this thread group


has been destroyed.

13) void list() This method prints information about


the thread group to the standard
output.
14) boolean parentOf(ThreadGroup This method tests if the thread group
g is either the thread group argument
or one of its ancestor thread groups.

15) void suspend() This method is used to suspend all


threads in the thread group.

16) void resume() This method is used to resume all


threads in the thread group which
was suspended using suspend()
method.

17) void setMaxPriority(int pri) This method sets the maximum


priority of the group.

18) void stop() This method is used to stop all


threads in the thread group.

19) String toString() This method returns a string


representation of the Thread group.

ThreadGroup tg1 = new ThreadGroup("Group A");


Thread t1 = new Thread(tg1,new MyRunnable(),"one");
Thread t2 = new Thread(tg1,new MyRunnable(),"two");
Thread t3 = new Thread(tg1,new MyRunnable(),"three");
Now all 3 threads belong to one group.
Here, tg1 is the thread group name, MyRunnable is the class that implements
Runnable interface and "one", "two" and "three" are the thread names.
Now we can interrupt all threads by a single line of code only.
Thread.currentThread().getThreadGroup().interrupt();

ThreadGroup Example
File: ThreadGroupDemo.java
public class ThreadGroupDemo implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");

Thread t1 = new Thread(tg1, runnable,"one");


t1.start();
Thread t2 = new Thread(tg1, runnable,"two");
t2.start();
Thread t3 = new Thread(tg1, runnable,"three");
t3.start();

System.out.println("Thread Group Name: "+tg1.getName());


tg1.list();

}
}
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]

Priority of a Thread (Thread Priority)


Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, the thread scheduler schedules the threads according to their priority
(known as preemptive scheduling).
But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.
Note that not only JVM a Java programmer can also assign the priorities of a thread
explicitly in a Java program.
Setter & Getter Method of Thread Priority
The setter and getter method of the thread priority.
public final int getPriority(): The java.lang.Thread.getPriority() method returns the
priority of the given thread.
public final void setPriority(int newPriority): The java.lang.Thread.setPriority()
method updates or assign the priority of the thread to newPriority.
The method throws IllegalArgumentException if the value newPriority goes out of the
range, which is 1 (minimum) to 10 (maximum).

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1
and the value of MAX_PRIORITY is 10.

Example of priority of a Thread:


FileName: ThreadPriorityExample.java
// Importing the required classes
import java.lang.*;
public class ThreadPriorityExample extends Thread
{
// Method 1
// Whenever the start() method is called by a thread the run() method is invoked
public void run()
{
// the print statement
System.out.println("Inside the run() method");
}

// the main method


public static void main(String argvs[])
{
// Creating threads with the help of ThreadPriorityExample class
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();

// We did not mention the priority of the thread.


// Therefore, the priorities of the thread is 5, the default value

// 1st Thread
// Displaying the priority of the thread
// using the getPriority() method
System.out.println("Priority of the thread th1 is : " + th1.getPriority());

// 2nd Thread
// Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// 3rd Thread
// // Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// Setting priorities of above threads by


// passing integer arguments
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);

// 6
System.out.println("Priority of the thread th1 is : " + th1.getPriority());

// 3
System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// 9
System.out.println("Priority of the thread th3 is : " + th3.getPriority());

// Main thread
// Displaying name of the currently executing thread
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());

// Priority of the main thread is 10 now


Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
}
}
Output:
Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10

We know that a thread with high priority will get preference over lower priority threads
when it comes to the execution of threads.
However, there can be other scenarios where two threads can have the same priority.
All of the processing, in order to look after the threads, is done by the Java thread
scheduler.

Daemon Thread in Java


Daemon thread in Java is a service provider thread that provides services to the user
thread.
Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.
There are many java daemon threads running automatically
e.g. gc, finalizer etc.
By typing the jconsole in the command prompt we will get the details.
The jconsole tool provides information about the loaded classes, memory usage,
running threads etc.

Points to remember for Daemon Thread in Java


 It provides services to user threads for background supporting tasks. It has no role in
life than to serve user threads.
 Its life depends on user threads.
 It is a low priority thread.

Why JVM terminates the daemon thread if there is no user


thread?
The sole purpose of the daemon thread is that it provides services to user thread
for background supporting task.
If there is no user thread, why should JVM keep running this thread.
That is why JVM terminates the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java daemon thread.

No. Method Description

1) public void setDaemon(boolean is used to mark the current thread as daemon


status) thread or user thread.
2) public boolean isDaemon() is used to check that current is daemon.

Simple example of Daemon thread in java


File: MyThread.java
public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){ //checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true); //now t1 is daemon thread
t1.start(); //starting threads
t2.start();
t3.start();
}
}
Output:
daemon thread work
user thread work
user thread work

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.

Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. It can be achieved by using the following three ways:
1. By Using Synchronized Method
2. By Using Synchronized Block
3. By Using Static Synchronization

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor.
Every object has a lock associated with it.
By convention, a thread that needs consistent access to an object's fields has to acquire the
object's lock before accessing them, and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Understanding the problem without


Synchronization
In this example, there is no synchronization, so output is inconsistent.

TestSynchronization1.java
class Table{
void printTable(int n){ //method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
100
10
200
15
300
20
400
25
500

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.
TestSynchronization2.java
//example of java synchronized method
class Table{
synchronized void printTable(int n){ //synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronization2{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500

Producer Consumer Problem


Java program that implements producer consumer problem.
It is an example for multi process synchronization, where producer always
produces and consumer always consumes.
The consumer consumes only after the producer produces.

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.

Lab program 16:-


Write a JAVA program using Synchronized Threads, which demonstrates
Producer Consumer concept.
class Q
{
int n;
boolean valueSet = false;
synchronized int get()
{
while(!va
lueSet) try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}

synchronized void put(int n)


{
while(valueSet)
try

{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n =
n; va
lueSet = true;
System.out.println("Put: " +
n); notify();
}
}

class Producer implements Runnable


{
Q q;
Producer (Q q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run ()
{
int i =
1; wh
ile(i<10)
{ q.put(i++);

}
}
}

class Consumer implements Runnable


{
Q q;
Consumer(Q q)
{
this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{
int j = 1;
while(j<10)
{
q.get();
}
}
}

class prog5q
{
public static void main(String args[])
{
Q q = new
Q(); new
Producer(q); new
Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

Output:

Java File Handling


In Java, with the help of File Class, we can work with files.
This File Class is inside the java.io package.
The File class can be used by creating an object of the class and then specifying the name of
the file.
Why File Handling is Required?
File Handling is an integral part of any programming language as file handling enables us to
store the output of any particular program in a file and allows us to perform certain operations
on it.
In simple words, file handling means reading and writing data to a file.

File Operations in Java


In Java, a File is an abstract data type.

A named location used to store related information is known as a File.

There are several File Operations like creating a new File, getting information
about File, writing into a File, reading from a File and deleting a File.

Before understanding the File operations, it is required that we should have knowledge
of Stream and File methods.

Stream
A series of data is referred to as a stream.

In Java, Stream is classified into two types, i.e., Byte Stream and Character Stream.
Byte Stream
Byte Stream is mainly involved with byte data. A file handling process with a byte
stream is a process in which an input is provided and executed with the byte data.

Character Stream
Character Stream is mainly involved with character data. A file handling process with
a character stream is a process in which an input is provided and executed with the
character data.

To get more knowledge about the stream, click here.

Java File Class Methods

S.No. Method Return Descrip on


Type
1. canRead() Boolean The canRead() method is used to check whether we can read the
data of the file or not.

2. createNewFile() Boolean The createNewFile() method is used to create a new empty file.

3. canWrite() Boolean The canWrite() method is used to check whether we can write the
data into the file or not.

4. exists() Boolean The exists() method is used to check whether the specified file is
present or not.

5. delete() Boolean The delete() method is used to delete a file.

6. getName() String The getName() method is used to find the file name.

7. getAbsolutePath() String The getAbsolutePath() method is used to get the absolute


pathname of the file.

8. length() Long The length() method is used to get the size of the file in bytes.

9. list() String[] The list() method is used to get an array of the files available in the
directory.

10. mkdir() Boolean The mkdir() method is used for creating a new directory.

File Operations
We can perform the following operation on a file:

o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File
Create a File
Create a File operation is performed to create a new file. We use
the createNewFile() method of file. The createNewFile() method returns true when
it successfully creates a new file and returns false when the file already exists.

Let's take an example of creating a file to understand how we can use


the createNewFile() method to perform this operation.

CreateFile.java

// Importing File class


import java.io.File;
// Importing the IOException class for handling errors
import java.io.IOException;
class CreateFile {
public static void main(String args[]) {
try {
// Creating an object of a file
File f0 = new File("D:FileOperationExample.txt");
if (f0.createNewFile()) {
System.out.println("File " + f0.getName() + " is created successfully.");
} else {
System.out.println("File is already exist in the directory.");
}
} catch (IOException exception) {
System.out.println("An unexpected error is occurred.");
exception.printStackTrace();
}
}
}

Output:
In the above code, we import the File and IOException class for performing file operation and
handling errors, respectively. We create the f0 object of the File class and specify the location
of the directory where we want to create a file. In the try block, we call
the createNewFile() method through the f0 object to create a new file in the specified
location. If the method returns false, it will jump to the else section. If there is any error, it gets
handled in the catch block.

Write to a File
The next operation which we can perform on a file is "writing into a file".

In order to write data into a file, we will use the FileWriter class and its write() method
together.

We need to close the stream using the close() method to retrieve the allocated
resources.

Let's take an example to understand how we can write data into a file.

WriteToFile.java
// Importing the FileWriter class
import java.io.FileWriter;

// Importing the IOException class for handling errors


import java.io.IOException;

class WriteToFile {
public static void main(String[] args) {

try {
FileWriter fwrite = new FileWriter("D:FileOperationExample.txt");
// writing the content into the FileOperationExample.txt file
fwrite.write("A named location used to store related information is referred to as a File.")
;

// Closing the stream


fwrite.close();
System.out.println("Content is successfully wrote to the file.");
} catch (IOException e) {
System.out.println("Unexpected error occurred");
e.printStackTrace();
}
}
}

Output:
I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast.
The java.io package contains all the classes required for input and output operations.
We can perform file handling in Java by Java I/O API.

Stream
A stream is a sequence of data.
In Java, a stream is composed of bytes.
It's called a stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically.
All these streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream

To print output and an error message to the console.


System.out.println("simple message");
System.err.println("error message");

The code to get input from console.


int i=System.in.read(); //returns ASCII code of 1st character
System.out.println((char)i); //will print the character

OutputStream vs InputStream

OutputStream

Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.

InputStream

Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.

Working of Java OutputStream and InputStream by the figure given below.

OutputStream class
OutputStream class is an abstract class.
It is the superclass of all classes representing an output stream of bytes.
An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream


Method Description

1) public void write(int) throws IOException is used to write a byte to the current output
stream.

2) public void write(byte[]) throws IOException is used to write an array of byte to the current
output stream.

3) public void flush() throws IOException flushes the current output stream.

4) public void close() throws IOException is used to close the current output stream.

InputStream class
InputStream class is an abstract class.
It is the superclass of all classes representing an input stream of bytes.

Useful methods of InputStream

Method Description
1) public abstract int read() throws IOException reads the next byte of data from the input stream.
It returns -1 at the end of the file.

2) public int available() throws IOException returns an estimate of the number of bytes that
can be read from the current input stream.

3) public void close() throws IOException is used to close the current input stream.

Java FileOutputStream Class


Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class.
You can write byte-oriented as well as character-oriented data through FileOutputStream
class.
But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.

FileOutputStream class declaration

The declaration for Java.io.FileOutputStream class:


public class FileOutputStream extends OutputStream

FileOutputStream class methods


Method Description

protected void finalize() It is used to clean up the connection with the file output stream.

void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
output stream.

void write(byte[] ary, int off, It is used to write len bytes from the byte array starting at offset off to
int len) the file output stream.

void write(int b) It is used to write the specified byte to the file output stream.

FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.

FileDescriptor getFD() It is used to return the file descriptor associated with the stream.

void close() It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
A

Java FileOutputStream example 2: write string


import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data Welcome to javaTpoint.
testout.txt
Welcome to javaTpoint.

Java FileInputStream Class


Java FileInputStream class obtains input bytes from a file.
It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video
etc.
You can also read character-stream data.
But, for reading streams of characters, it is recommended to use FileReader class.

Java FileInputStream class declaration


The declaration for java.io.FileInputStream class:
public class FileInputStream extends InputStream

Java FileInputStream class methods

Method Description

int available() It is used to return the estimated number of bytes that can be
read from the input stream.

int read() It is used to read the byte of data from the input stream.

int read(byte[] b) It is used to read up to b.length bytes of data from the input
stream.

int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input stream.

long skip(long x) It is used to skip over and discards x bytes of data from the
input stream.

FileChannel getChannel() It is used to return the unique FileChannel object associated


with the file input stream.

FileDescriptor getFD() It is used to return the FileDescriptor object.

protected void finalize() It is used to ensure that the close method is call when there is no
more reference to the file input stream.

void close() It is used to closes the stream.

Java FileInputStream example 2: read all characters

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
Welcome to javaTpoint

Java BufferedOutputStream Class


Java BufferedOutputStream class is used for buffering an output stream. It internally uses
buffer to store data. It adds more efficiency than to write data directly into a stream. So, it
makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the
syntax for adding the buffer in an OutputStream:
1. OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testo
ut.txt"));
Java BufferedOutputStream class declaration
The declaration for Java.io.BufferedOutputStream class:
public class BufferedOutputStream extends FilterOutputStream

Java BufferedOutputStream class constructors

Constructor Description

BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for
writing the data to the specified output stream.

BufferedOutputStream(OutputStream os, It creates the new buffered output stream which is used for
int size) writing the data to the specified output stream with a
specified buffer size.
Java BufferedOutputStream class methods

Method Description

void write(int b) It writes the specified byte to the buffered output stream.

void write(byte[] b, int It write the bytes from the specified byte-input stream into a specified
off, int len) byte array, starting with the given offset

void flush() It flushes the buffered output stream.

Java BufferedInputStream Class


Java BufferedInputStream class is used to read information from stream. It internally uses
buffer mechanism to make the performance fast.
The important points about BufferedInputStream are:
o When the bytes from the stream are skipped or read, the internal buffer automatically
refilled from the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer array is created.

Java BufferedInputStream class declaration


The declaration for Java.io.BufferedInputStream class:
public class BufferedInputStream extends FilterInputStream

Java BufferedInputStream class constructors

Constructor Description

BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it argument, the


input stream IS, for later use.
BufferedInputStream(InputStream IS, It creates the BufferedInputStream with a specified buffer
int size) size and saves it argument, the input stream IS, for later use.

Java BufferedInputStream class methods

Method Description

int available() It returns an estimate number of bytes that can be read from the
input stream without blocking by the next invocation method for
the input stream.

int read() It read the next byte of data from the input stream.

int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream into a
specified byte array, starting with the given offset.

void close() It closes the input stream and releases any of the system resources
associated with the stream.

void reset() It repositions the stream at a position the mark method was last
called on this input stream.

void mark(int readlimit) It sees the general contract of the mark method for the input stream.

long skip(long x) It skips over and discards x bytes of data from the input stream.

boolean markSupported() It tests for the input stream to support the mark and reset methods.

import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
javaTpoint
Output:
javaTpoint

Java DataOutputStream Class


Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by
a data input stream.

Java DataOutputStream class declaration

The declaration for java.io.DataOutputStream class:


public class DataOutputStream extends FilterOutputStream implements DataOutput

Java DataOutputStream class methods


Method Description

int size() It is used to return the number of bytes written to the data
output stream.

void write(int b) It is used to write the specified byte to the underlying output
stream.

void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream.

void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte


value.

void writeChar(int v) It is used to write char to the output stream as a 2-byte


value.

void writeChars(String s) It is used to write string to the output stream as a sequence


of characters.

void writeByte(int v) It is used to write a byte to the output stream as a 1-byte


value.

void writeBytes(String s) It is used to write string to the output stream as a sequence of


bytes.

void writeInt(int v) It is used to write an int to the output stream

void writeShort(int v) It is used to write a short to the output stream.


void writeLong(long v) It is used to write a long to the output stream.

void writeUTF(String str) It is used to write a string to the output stream using UTF-
8 encoding in portable manner.

void flush() It is used to flushes the data output stream.

Example of DataOutputStream class

In this example, we are writing the data to a text file testout.txt using DataOutputStream class.
import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
Output:
Succcess...
testout.txt:
A
Java DataInputStream Class
Java DataInputStream class allows an application to read primitive data from the input stream
in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by a
data input stream.

Java DataInputStream class declaration


The declaration for java.io.DataInputStream class:
public class DataInputStream extends FilterInputStream implements DataInput

Java DataInputStream class Methods

Method Description

int read(byte[] b) It is used to read the number of bytes from the input stream.

int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.

int readInt() It is used to read input bytes and return an int value.

byte readByte() It is used to read and return the one input byte.

char readChar() It is used to read two input bytes and returns a char value.

double readDouble() It is used to read eight input bytes and returns a double value.

boolean readBoolean() It is used to read one input byte and return true if byte is non zero,
false if byte is zero.

int skipBytes(int x) It is used to skip over x bytes of data from the input stream.

String readUTF() It is used to read a string that has been encoded using the UTF-8
format.

void readFully(byte[] b) It is used to read bytes from the input stream and store them into
the buffer array.
void readFully(byte[] b, int off,
It is used to read len bytes from the input stream.
int len)

Example of DataInputStream class


In this example, we are reading the data from the file testout.txt file.

package com.javatpoint;
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
JAVA
Output:
J-A-V-A

Java - RandomAccessFile
This class is used for reading and writing to random access file.
A random access file behaves like a large array of bytes.
There is a cursor implied to the array called file pointer, by moving the cursor we do the read
write operations.
If end-of-file is reached before the desired number of byte has been read than EOFException
is thrown. It is a type of IOException.

Constructor

Constructor Description

RandomAccessFile(File file, String mode) Creates a random access file stream to read from,
and optionally to write to, the file specified by the
File argument.

RandomAccessFile(String name, String mode) Creates a random access file stream to read from,
and optionally to write to, a file with the specified
name.

Modifier Method Method


and Type

void close() It closes this random access file stream and releases
any system resources associated with the stream.

FileChannel getChannel() It returns the unique FileChannel object associated


with this file.

int readInt() It reads a signed 32-bit integer from this file.

String readUTF() It reads in a string from this file.

void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
void writeDouble(double v) It converts the double argument to a long using the
doubleToLongBits method in class Double, and then
writes that long value to the file as an eight-byte
quantity, high byte first.

void writeFloat(float v) It converts the float argument to an int using the


floatToIntBits method in class Float, and then writes
that int value to the file as a four-byte quantity, high
byte first.

void write(int b) It writes the specified byte to this file.

int read() It reads a byte of data from this file.

long length() It returns the length of this file.

void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.

Example

import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}

The myFile.TXT contains text "This class is used for reading and writing to random access
file."
after running the program it will contains
This class is used for reading I love my country and my peoplele.

Applets

 Java programs are classified into two ways


 Applications program
 Application programs are those programs which are
normally created, compiled and executed as similar to the
other languages.
 Each application program contains one main( ) method
 Programs are created in a local computer.
 Programs are compiled with javac compiler and executed
in java interpreter.

 Applet program
 An applet is a special program that we can embedded in
a web page such that the applet gains control over a certain
part of the displayed page.
 It is differ from application program
 Applets are created from classes
 An applet do not have main as an entry. Instead have
several methods to control specific aspects of applet
execution.

Class Hierarchy of Applet

 Every applet that we are creating must be a sub class of Applet.


 This Applet is extended from Panel.
 This Panel is extended from Container.
 The Container class extends Component class.
 Component class is extending from Object class which is parent
of all Java API classes
Java.lang.Object

Java.awt.Component

Java.awt.Container

Java.awt.Panel

Java.applet.Applet

About Java.awt.Component

• java.lang.Object
• java.awt.Component
• public abstract class Component extends Object implements
ImageObserver, MenuContainer, Serializable
• A component is an object having a graphical representation that
can be displayed on the screen and that can interact with the
user.
• Examples of components are the buttons, checkboxes, and
scrollbars of a typical graphical user interface.

About Java.awt.Container

• java.lang.Object
• java.awt.Component
 java.awt.Container

• public class Container extends Component


• A generic Abstract Window Toolkit(AWT) container object is a
component that can contain other AWT components.
• Components added to a container are tracked in a list. The order
of the list will define the components' front-to-back stacking
order within the container. If no index is specified when adding
a component to a container, it will be added to the end of the
list (and hence to the bottom of the stacking order).  Example
: Add()

About Java.awt.Panel

• java.lang.Object
• java.awt.Component
 java.awt.Container
• java.awt.Panel
• public class Panel extends Container implements Accessible
• Panel is the simplest container class.
• A panel provides space in which an application can attach any
other component, including other panels.
• The default layout manager for a panel is the FlowLayout layout
manager.

 Java.applet.Applet
• java.lang.Object
• java.awt.Component
 java.awt.Container
 java.awt.Panel
o java.applet.Applet
 public class Applet extends Panel
o An applet is a small program
that is intended not to be run on its own,
but rather to be embedded inside another
application.
o The Applet class must be the superclass of any applet
that is to be embedded in a Web page or viewed by the
Java Applet Viewer. The Applet class provides a
standard interface between applets and their
environment.

Example - 1

impor
t
java.a
wt.*;
impor
t
java.a
pplet.
*;
public class myapplet extends Applet
{
public void paint(Graphics g)

drawString("Welcome to applet",30,30);

--------------------------------
Html file

<html>
<head>
<body>
<applet code = "myapplet.class"
width=200 height=100> abcd
</applet>
</body>
</head>

Execution procedure of applet program

• Save the above program with myapplet.java


• Compile the program using
o Javac myapplet.java
• In order to run the program there are two methods
o Using web browser
• executing the applet through html within a java compatible
browser such as HotJava, Netscape Navigator or Internet
explorer.
• To execute this method, we need write the HTML file with
Applet tag.
 Save the program with test.html.
 Open web browser, and type path of file at address
bar
o From console
 At the console window give the following command
 Appletviewer test.html
Method – 2
impor
t
java.a
wt.*;
impor
t
java.a
pplet.
*;
public class myapplet extends Applet
{
public void paint(Graphics g)
{

drawString("Welcome toapplet",30,30);

}
}
/*
<applet code = "myapplet.class" width = 200 height = 100>
<
/
a
p
p
l
e
t
>
*
/
• Save the above program with myapplet.java
• Compile it using javac myapplet.java
• Run using appletviewer myapplet.java

Architecture of an Applet

• Since applet is an window based program.


• Its architecture is different from the console based programs.
• In window based program we must understand few concepts:
o First, applets are event driven.
o how the event-driven architecture impacts the design of an
applet.
o An applet resembles a set of interrupt service routines.

Here is how the process works.


 An applet waits until an event occurs.
 The AWT notifies the applet about an event by calling
an event handler that has been provided by the applet.
 Once this happens, the applet must take appropriate
action and then quickly return control to the AWT.
 This is a crucial point. For the most part, your applet
should not enter a ―mode of operation in which
it maintains control for an extended period.
 Instead, it must perform specific actions in response
to events and then return control to the AWT run-time
system.
 In those situations in which your applet needs to
perform a repetitive task on its own (for example,
displaying a scrolling message across its window), you
must start an additional thread of execution.
o Second, the user initiates interaction with an applet—not the
other way around.
 As you know, in a no windowed program, when the
program needs input, it will prompt the user and then
call some input method, such as readLine( ).
 This is not the way it works in an applet.
 Instead, the user interacts with the applet as he or she
wants, when he or she wants. These interactions are
sent to the applet as events to which the applet must
respond.
o For example, when the user clicks a mouse
inside the applet’s window, a mouse-clicked
event is generated.
o If the user presses a key while the applet’s
window has input focus, a keypress event is
generated.
o applets can contain various controls, such as
push buttons and check boxes. When the user
interacts with one of these controls, an event is
generated.

Applet Skelton [Applet Life Cycle]

 All but the most trivial applets override a set of methods that
provides the basic mechanism by which the browser or
applet viewer interfaces to the applet and controls its
execution. Four of these methods—init( ), start( ), stop( ),
and destroy( )—are defined by Applet. Another, paint( ), is
defined by the AWT Component class.

 Default implementations for all of these methods are


provided.
 Applets do not need to override those methods they do
not use.
 only very simple applets will not need to define all of
them.

 These five methods can be assembled into the skeleton


shown here:

// An Appletskeleton.

import java.awt.*;

import java.applet.*;

/*

<applet code="AppletSkel" width=300 height=100>

</applet> */

public class AppletSkel extends Applet

{ // Called first.

public void init()

// initialization

/* Called second, after init(). Also called whenever the applet is


restarted. */

public void start()

{ // start or resume execution


}

// Called when the applet is stopped.

public void stop()

{ // suspends execution

/* Called when applet is terminated. This is the last method


executed. */

public void destroy()

{ // perform shutdown activities

// Called when an applet's window must be restored.

public void paint(Graphics g)

{ // redisplay contents of window

Although this skeleton does not do anything, it can be compiled and run.

When run, it generates the following window when viewed with an applet
viewer:
Applet Initialization and Termination

When an applet begins, the AWT calls the


following methods, 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( )

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.

start( )
The start( ) method is called after init( ).
It is also called to restart an applet after it has been stopped.
Whereas init( ) is called once—the first time an applet is
loaded—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( ).

paint( )
The paint( ) method is called each time your 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.

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.

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

Overriding update( )
In some situations, applet may need to override another
method defined by theAWT, called update( ).
This method is called when your applet has requested that a
portion of its window be redrawn.
The default version of update( ) first fills an applet with the
default background color and then calls paint( ).
If you fill the background using a different color in paint( ),
the user will experience a flash of the default background
each time update( ) is called—that is, whenever the window
is repainted.
One way to avoid this problem is to override the update( )
method so that it performs all necessary display activities.
Then have paint( ) simply call update( ).
Thus, for some applications, the applet skeleton will override
paint( ) and update( ), as shown here:

public void update(Graphics g)


{ // redisplay your window, here.
}
public void
paint(Graphics g)
{ update(g);
}

To output a string to an applet, use drawString( ), which is a


member of the Graphics class.
Typically, it is called from within either update( ) or paint( ).
It has the following general form:
o void drawString(String message, int x, int y)
 Here, message is the string to be output beginning at x,y.
In a Java window, the upper-left corner is location 0,0.
The drawString( ) method will not recognize newline
characters.
If you want to start a line of text on another line, you must
do so manually, specifying the precise X,Y location where
you want the line to begin.
 To set the background color of an applet’s
window, use
 setBackground( ).
 To set the foreground color use
 setForeground( ).
 These methods are defined by Component, and they have
the following general forms:
o void
setBackground(Color
newColor)
o void
setForeground(Color
newColor)
 Here, newColor specifies the new color.
 The class Color defines the constants shown here that can be used to
specify colors:

o Color.black
o Color.magenta
o Color.blue
o Color.orange
o Color.cyan
o Color.pink
o Color.darkGra
o Color.red
o Color.gray
o Color.white
o Color.green
o Color.yellow
o Color.lightGray

For example, this sets the background color to green and the text color to
red:
 setBackground(Color.green);
 setForeground(Color.red);
 We has to set the foreground and background colors is in the
init( ) method o we can change these colors during execution
of program also
 The default foreground color is black.
o The default background color is light gray.
o we can obtain the current settings for the background and
foreground colors by calling getBackground( ) and
getForeground( ), respectively.

They are also defined by Component and are shown here:


o Color getBackground( )
o Color getForeground( )

Program
/* A simple applet that sets the foreground and background colors and outputs a
string. */

import java.awt.*;

import java.applet.*;

/*

<applet code="Sample" width=300 height=50>

</applet> */
public class Sample extends Applet{

String msg;

// set the foreground and background colors.

public void init()

{ setBackground(Color.cyan); setForeground(Color.red); msg = "Inside init( ) --";

// Initialize the string to be displayed.

public void start()

{ msg += " Inside start( ) --";

// Display msg in applet window.

public void paint(Graphics g)

{ msg += " Inside paint( ).";

g.drawString(msg, 10, 30);

Using Repaint method


• As a general rule, an applet writes to its window only
when its
update( ) or paint( ) method is called by the AWT.
• How can the applet itself cause its window to be updated
when its information changes?
For example, if an applet is displaying a moving banner,
what mechanism does the applet use to update the
window each time this banner scrolls?
• It cannot create a loop inside paint( ) that repeatedly
scrolls the banner
• The repaint( ) method is defined by the AWT.
• It causes the AWT run-time system to execute a call to
your applet’s update( ) method, which, in its default
implementation, calls paint( )
• The repaint( ) method has four forms.
• The simplest version of repaint( ) is shown here:
o void repaint( )
• This version causes the entire window to be repainted.
• The following version specifies a region that will be
repainted:
o void repaint(int left, int top, int width, int height)
• Here, the coordinates of the upper-left corner of the
region are specified by left and top, and the width and
height of the region are passed in width and height.
These dimensions are specified in pixels
• Calling repaint( ) is essentially a request that your applet
be repainted sometime soon.
However, if your system is slow or busy, update( ) might
not be called immediately.
Multiple requests for repainting that occur within a short
time can be collapsed by the AWT in a manner such that
update( ) is only called sporadically.
This can be a problem in many situations, including
animation, in which a consistent update time is
necessary.
One solution to this problem is to use the following forms
of repaint( ):
o void repaint(long maxDelay)
o void repaint(long maxDelay, int x, int y, int width,
int height)
• Here, maxDelay specifies the maximum number of
milliseconds that can elapse before update( ) is called
Program
/* A simple banner applet.

This applet creates a thread that scrolls the message contained in msg right to left
across the applet's window.

*/

import java.awt.*;

import java.applet.*;

/*

<applet code="SimpleBanner" width=300 height=50>

</applet>

*/

public class SimpleBanner extends Applet implements Runnable {

String msg = " A Simple Moving Banner.";

Thread t = null; int state; boolean stopFlag;

// Set colors and initialize thread.

public void init()

{ setBackground(Color.cyan);

setForeground(Color.red);

// Start thread

public void start()

{ t = new Thread(this);

stopFlag = false; t.start();


}

// Entry point for the thread that runs the banner.

public void run()

{ char ch;

// Display banner

for( ; ; )

try { repaint();

Thread.sleep(250);

ch = msg.charAt(0);

msg = msg.substring(1, msg.length());

msg += ch;

if(stopFlag) break;

} catch(InterruptedException e) {}

// Pause the banner.

public void stop()

{ stopFlag = true;

t = null;

// Display the banner.

public void paint(Graphics g)

{ g.drawString(msg, 50, 30);


}

Using Status window

• In addition to displaying information in its window, an


applet can also output a message to the status window of
the browser or applet viewer on which it is running.
• To do so, call showStatus( ) with the string that you want
displayed. The status window is a good place to give the
user feedback about what is occurring in the applet,
suggest options, or possibly report some types of errors.
The status window also makes an excellent debugging
aid, because it gives you an easy way to output
information about your applet.

// Using the Status Window.

import java.awt.*;

import java.applet.*;

/*

<applet code="StatusWindow" width=300 height=50>

</applet>

*/

public class StatusWindow extends Applet{

public void init()

{ setBackground(Color.cyan);
}

// Display msg in applet window.

public void paint(Graphics g)

drawString("This is in the applet window.", 10, 20);

showStatus("This is shown in the status window.");

Syntax of Applet tag in HTML

The syntax for the standard APPLET tag is shown here.


Bracketed items are optional.

< APPLET
[CODEBASE = codebaseURL]

CODE = appletFile

[ALT = alternateText]

[NAME = appletInstanceName]
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>

[< PARAM NAME = AttributeName VALUE =


AttributeValue>]

[< PARAM NAME = AttributeName2 VALUE =


AttributeValue>]

...

[HTML Displayed in the absence of Java]

</APPLET>

CODEBASE
CODEBASE is an optional attribute that specifies the base URL of
the applet code, which is the directory that will be searched for the
applet’s executable class file (specified by the CODE tag).
The HTML document’s URL directory is used as the CODEBASE if
this attribute is not specified.
The CODEBASE does not have to be on the host from which the
HTML document was read.

CODE
CODE is a required attribute that gives the name of the file
containing your applet’s compiled .class file.
This file is relative to the code base URL of the applet, which is the
directory that the HTML file was in or the directory indicated by
CODEBASE if set.
ALT
The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser understands the
APPLET tag but can’t currently run Java applets.
This is distinct from the alternate HTML you provide for browsers
that don’t support applets.

NAME
NAME is an optional attribute used to specify a name for the applet
instance. Applets must be named in order for other applets on the
same page to find them by name and communicate with them.
To obtain an applet by name, use getApplet( ), which is defined by
the AppletContext interface.

WIDTH AND HEIGHT


WIDTH and HEIGHT are required attributes that give the size (in
pixels) of the applet display area.
ALIGN ALIGN is an optional attribute that specifies the alignment
of the applet. This attribute is treated the same as the HTML IMG
tag with these possible values: LEFT, RIGHT, TOP, BOTTOM,
MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.

VSPACE AND HSPACE


These attributes are optional. VSPACE specifies the space, in
pixels, above and below the applet.
HSPACE specifies the space, in pixels, on each side of the applet.
They’re treated the same as the IMG tag’s VSPACE and HSPACE
attributes.

PARAM NAME AND VALUE


The PARAM tag allows you to specify applet specific arguments in an
HTML page. Applets access their attributes with the getParameter( )
method.

HANDLING OLDER BROWSERS


Some very old web browsers can’t execute applets and don’t
recognize the APPLET tag.
Although these browsers are now nearly extinct (having been
replaced by Java-compatible ones), may need to deal with them
occasionally.
The best way to design your HTML page to deal with such browsers
is to include HTML text and markup within your
<applet></applet> tags.
If the applet tags are not recognized by your browser, you will see
the alternate markup.
If Java is available, it will consume all of the markup between the
<applet></applet> tags and disregard the alternate markup.

Here’s the HTML to start an applet called SampleApplet in Java


and to display a message in older browsers:

<applet code="SampleApplet" width=200 height=40>

If you were driving a Java powered browser, you'd see &quote;

A Sample Applet&quote; here.

<p>

</applet>
Passing Parameters to Applets:

 the APPLET tag in HTML allows you to pass parameters to


your applet.
 To retrieve a parameter, use the getParameter( ) method.
 It returns the value of the specified parameter in the form of
a String object. Thus, for numeric and boolean values, you
will need to convert their string representations into their
internal formats.

// Use Parameters

import java.awt.*;

import java.applet.*;

/*

<applet code="ParamDemo" width=300 height=80>

<param name=fontName value=Courier>

<param name=fontSize value=14>

<param name=leading value=2>

<param name=accountEnabled value=true>

</applet>

*/

public class ParamDemo extends Applet{

String fontName;

int fontSize;

float leading;
boolean active;

// Initialize the string to be displayed.

public void start()

{ String param;

fontName = getParameter("fontName");

if(fontName == null)

fontName = "Not Found";

param = getParameter("fontSize");

try {

if(param != null) // if not found

fontSize = Integer.parseInt(param);

else

fontSize = 0;

} catch(NumberFormatException e) {

fontSize = -1;

param = getParameter("leading");

try { if(param != null) // if not found

leading = Float.valueOf(param).floatValue();

else

leading = 0;

} catch(NumberFormatException e)
{ leading = -1; }

param = getParameter("accountEnabled");

if(param != null)

active = Boolean.valueOf(param).booleanValue();

// Display parameters.

public void paint(Graphics g)

g.drawString("Font name: " + fontName, 0, 10);

g.drawString("Font size: " + fontSize, 0, 26);

g.drawString("Leading: " + leading, 0, 42);

g.drawString("Account Active: " + active, 0, 58);

You might also like