Sunteți pe pagina 1din 33

VTU

7th sem B.E (CSE/ISE)

JAVA/ J2EE

Notes prepared by
Mr. Ashok Kumar K
9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

Unit 3:

Multithreaded Programming,
Event Handling

Mr. Ashok Kumar K


9742024066 | celestialcluster@gmail.com

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

15 reasons to choose VTUPROJECTS.COM for your final year project work

1. Training from the scratch


We train our students on all the languages and technologies required for developing the projects from the
scratch. No prerequisites required.
2. Line by Line code explanation
Students will be trained to such an extent where they can explain the entire project line by line code to their
respective colleges.
3. Study Materials
We provide the most efficient study material for each and every module during the project development
4. Trainers
Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter
expert in strengthening student's skillset for cracking any interviews. He will be having a thorough experience
in working on both product and service driven industries.
5. Reports and PPTs
Project report as per the university standards and the final presentation slides will be provided and each
student will be trained on the same.
6. Video manuals
Video manuals will be provided which will be useful in installing and configuring various softwares during
project development
7. Strict SDLC
Project development will be carried out as per the strict Software Development model
8. Technical Seminar topics
We help students by providing current year's IEEE papers and topics of their wish for their final semester
Technical seminars
9. Our Availability
We will be available at our centers even after the class hours to help our students in case they have any
doubts or concerns.
10. Weightage to your Resume
Our students will be adding more weightage to their resumes since they will be well trained on various
technologies which helps them crack any technical interviews
11. Skype/ Team viewer support
In case the student needs an emergency help when he/she is in their colleges, we will be helping out them
through Skype/ Team viewer screen sharing
12. Practical Understanding
Each and module in the project will be implemented and taught to the students giving practical real world
applications and their use.
13. Mock demo and presentations
Each student will have to prepare for mock demo and presentations every week so that he/she will be
confident enough to demonstrate the project in their respective colleges
14. Communication & Soft skills Training
We provide communication and soft skills training to each students to help improve their presentation and
demonstration skills.
15. Weekly monitoring
Each student will be monitored and evaluated on the status of the project work done which helps the students
to obtain thorough understanding on how the entire project will be developed

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

MULTITHREADED PROGRAMMING

3.1 Multithreaded programming basics

Definition of concurrency (multithreading)

Concurrency is the ability to run multiple parts of the program in parallel. If a program can be divided into multiple independent parts,
each performing a specific task, then executing these parts in parallel in an asynchronous way increases the throughput of the program.
This type of programming is generally referred to as Concurrent Programming.

Process v/s Thread

In Concurrent programming, there are two units of execution:


 Processes
 Threads

Process Thread

Definition: Definition:
Process is an instance of an entire program Thread is an execution path or the control
in execution. flow of execution of a program.

A process has a separate execution Threads exist within a process; every process
environment. It has a complete, private set of has at least one thread. Threads share the
basic run-time resources; each process has process's resources, including memory and
its own memory space open files. Threads are called light-weight
process

Remember:

Threads have their own call stack and can access shared data. These cause two problems
 Visibility problem occurs if thread A reads shared data and thread B later changes this data and the thread A is unaware of this
change.
 Access problem can occur if several threads tries to access and share the same shared data at the same time.

3.2 Threads in Java

A separate process will be created for each Java program within which one default thread (called the Main thread) starts executing the
main function. This default thread or the main thread will be created by JVM. You can also create child threads using this.

Main thread is something which you should mark as important, because:

 It is the thread using which other threads (child threads) can be created
 Ideally it must be the last thread to finish execution because it performs various shutdown operations.

Each thread in java is associated with an instance of the class java.lang.Thread.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Let's play with main thread for some time. Remember, each thread will be having a name and priority (dealt later). A Thread can also
sleep, meaning go to IDLE state for some specified amount of time.

Below example does some exercise with the main thread. It first gets the access (reference) to main thread using currentThread()
method in Thread class. It prints the name of the thread whose reference we have just got. It changes the name and priority of the
thread using setName() and setPriority() methods respectively. It prints the numbers 0 through 4 with a delay of 1sec after each
number. The thread is made to sleep for 1 sec after printing one number. A thread can be sent to sleep using Thread.sleep(long)
method where the parameter is the amount of time in milliseconds.

public class Example {


public static void main(String arg[]) {
Thread t = Thread.currentThread();
System.out.println("Hi Everyone .. I am a thread .. " + t);
t.setName("NewMain");
t.setPriority(9);
System.out.println("Hi Everyone .. I am the same thread .. " + t);
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}

Output

When you simply print a thread reference t, you know that it will invoke t.getString() method which printed something like this:
Thread[main, 5, main]. Here is what actually they are:

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
3.3 Creating a Thread

Threads in java can be created in two possible ways

1. By implementing Runnable interface


2. By extending Thread class

Creating a thread by implementing Runnable interface

Step 1:

Simply define your own class and implement it by java.lang.Runnable interface. Define run() method and include the
business logic of the thread within the run() method, because run() is the entry point for a thread and when it returns
from this function, the thread dies. To put it differently, a thread will be active till it lies in the context of run() method.
Instance of this class is called Runnable object since it implements Runnable interface.

class MyThread implements Runnable {


public void run() {
System.out.println("Child thread started.. ");
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Child .. " + i);
}
System.out.println("Child thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Step 2:

Creating a child thread is nothing but creating an instance of Thread class and passing the runnable object as a
parameter for its constructor. Remember, at this point of time you have only created a child thread, but you haven't
started its execution yet. To do so, you should invoke start() method of the thread object you just created. It causes the
child thread to start its execution. The JVM calls run() method of the child thread. The result is that two threads are
running concurrently: the current thread (which returns from the call to the start method) and the other thread (which
executes its run() method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed
execution.

public class Example {


public static void main(String arg[]) {
// Runnable Object
MyThread m1 = new MyThread();

// Create a child thread


Thread t1 = new Thread(m1);

// Start (run) a child thread


t1.start();

try {
for (int i = 0; i < 5; i++) {
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
System.out.println("Main thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Output:

The order of execution of two threads is not the same always. The output you are seeing above can't be predicted.
Since the main thread and the child thread both are executing in parallel you can't expect the same ordering all the time.
It just gets mixed up.

Observation:

As a component developer you should focus on both the business logic and the required resources to create a thread.
An application developer will simply makes use of this. What I meant to tell is you should allow full freedom to the user of
this thread. You should encapsulate the process of creating a thread within the custom Thread class itself, as shown
below;

Here is the optimized version of above program

class MyThread implements Runnable {


Thread t;

MyThread() {
t = new Thread(this);
t.start();
}

public void run() {


System.out.println("Child thread started.. ");
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Child .. " + i);
}
System.out.println("Child thread exiting .. ");
} catch (InterruptedException e) {

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
e.printStackTrace();
}
}
}

public class Test {


public static void main(String arg[]) {
// Runnable Object
MyThread m1 = new MyThread();

try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
System.out.println("Main thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Creating a thread by extending Thread class

Step 1:

Simply extend your own class with java.lang.Thread. Define run() method and include the business logic of the
thread within the run() method, because run() is the entry point for a thread and when it returns from this function, the
thread dies.

class MyThread extends Thread {


public void run() {
System.out.println("Child thread started.. ");
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Child .. " + i);
}
System.out.println("Child thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Step 2:

Creating a thread is just creating an instance of the class defined in step 1. To begin the execution of the child thread,
you should invoke the run() method of the object created.

public class Test2 {


public static void main(String arg[]) {
// Runnable Object
MyThread m1 = new MyThread();
// Start a thread
m1.start();

try {
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
System.out.println("Main thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Observation:

As discusses previously, the logic of creating a thread should be encapsulated within the Thread class by the
component developer. Here is the optimized version of the above program.

class MyThread extends Thread {


MyThread() {
this.start();
}

public void run() {


System.out.println("Child thread started.. ");
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Child .. " + i);
}
System.out.println("Child thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class Test2 {


public static void main(String arg[]) {
// Runnable Object
MyThread m1 = new MyThread();

try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
System.out.println("Main thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Now that you have two different ways of creating a thread, which one would you prefer?

Creating a thread by implementing Runnable interface is preferred over extending the Thread class for two reasons.

 Inheritance should be done only if you are modifying or enhancing the base class behavior. Since our class doesn't modify or
enhance the Thread class behavior, extending the Thread class is not recommended.
 If you extend the Thread class, you now don't have freedom of extending other classes (since multiple inheritances are not
allowed). So we prefer implementing the Runnable interface and extending any other class.

Creating multiple threads

You can create as many threads as you want. Below example creates four threads and starts them so that the four child threads along
with the main thread prints the numbers 0 to 4 concurrently. One more thing you need to observe from below program is the method of
assigning a name to the child thread. Yes, you can set the name of a child thread by passing the name as a String argument to the
Thread class constructor.

class MyThread implements Runnable {


Thread t;

MyThread(String name) {
t = new Thread(this, name); // 'name' is the child thread's name
t.start();
}

public void run() {


System.out.println("New Thread started with the name
.."+Thread.currentThread().getName());
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" .. " + i);
}
System.out.println(Thread.currentThread().getName()+" exiting ..
");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class Test {


public static void main(String arg[]) {
// Runnable Object
MyThread m1 = new MyThread("ChildOne");
MyThread m2 = new MyThread("ChildTwo");
MyThread m3 = new MyThread("ChildThree");
MyThread m4 = new MyThread("ChildFour");

try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
System.out.println("Main thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

Output

You can clearly see the order in which these threads execute can't be predicted. It depends on many things including the thread
priority.

3.4 isAlive() and join()


Recall we had concluded that the main thread should be the last thread to terminate. But as we can see from the output of previous
program, main thread is being terminated well before its child threads terminate. Right, the problem in discussion here is, what are the
various ways to make the main thread to terminate at last?

There are three possible methods to make the main thread wait till all its child threads get terminated.

Let’s analyze each one of them.

Method 1:

Make the main thread to sleep for some specified amount of time just before its termination, so that all its child threads can

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
terminate by that time.

class MyThread implements Runnable {


Thread t;

MyThread(String name) {
t = new Thread(this, name);
t.start();
}

public void run() {


System.out.println("New Thread started with the name ..
"+Thread.currentThread().getName());
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" .. " + i);
}
System.out.println(Thread.currentThread().getName()+" exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class Test {


public static void main(String arg[]) {
// Runnable Object
MyThread m1 = new MyThread("ChildOne");
MyThread m2 = new MyThread("ChildTwo");
MyThread m3 = new MyThread("ChildThree");
MyThread m4 = new MyThread("ChildFour");

try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}

// Main Thread will sleep for 10 seconds


try {
Thread.sleep(10000);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("Main thread exiting .. ");
}

Output:

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

You can observe the main thread is terminating at last.

Drawback:

How will you choose the amount of time that the main thread should sleep to ensure the termination of all its child threads?

 You would end up choosing some large amount of time therefore making the main thread sleep for some extra time
even though all its child threads are already terminated.
 You would end up choosing lesser time giving no time for some of its child threads to terminate.

Method 2:

Using isAlive() method.

Main thread can invoke isAlive() method on each of its child threads to see if it is still running or already terminated. This
way, the main thread will be in a continuous loop until all the child threads gets terminated. isAlive() is a method defined in
Thread class and have the signature as follows:

final boolean isAlive()

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

It returns true if the thread upon which it is called is still running. It returns false otherwise.

Example

class MyThread implements Runnable {


Thread t;

MyThread(String name) {
t = new Thread(this, name);
t.start();
}

public void run() {


System.out.println("New Thread started with the name ..
"+Thread.currentThread().getName());
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" .. " + i);
}
System.out.println(Thread.currentThread().getName()+" exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class Test {


public static void main(String arg[]) {
// Runnable Object
MyThread m1 = new MyThread("ChildOne");
MyThread m2 = new MyThread("ChildTwo");
MyThread m3 = new MyThread("ChildThree");
MyThread m4 = new MyThread("ChildFour");

try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}

// Main Thread will come out of this loop only after all the threads
terminates
while (true) {
if (m1.t.isAlive() || m2.t.isAlive() || m3.t.isAlive() ||
m4.t.isAlive()) {
// loop again
}
else
break; // come out of the loop
}
System.out.println("Main thread exiting .. ");
}

Output

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

Drawback:

This method has unspecified amount of continuous looping to check the status of the child threads thus wasting the runtime
resources.

Method 3:

Using join() method.

join() is the method we mostly use to wait for a thread to finish its execution. join() method is also defined in Thread class
with the signature as follows:

final void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates. Additional forms of join( ) allow you to specify a
maximum amount of time that you want to wait for the specified thread to terminate.

Example

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
class MyThread implements Runnable {
Thread t;

MyThread(String name) {
t = new Thread(this, name);
t.start();
}

public void run() {


System.out.println("New Thread started with the name ..
"+Thread.currentThread().getName());
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" .. " + i);
}
System.out.println(Thread.currentThread().getName()+" exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class Example {


public static void main(String arg[]) {
// Runnable Object
MyThread m1 = new MyThread("ChildOne");
MyThread m2 = new MyThread("ChildTwo");
MyThread m3 = new MyThread("ChildThree");
MyThread m4 = new MyThread("ChildFour");

try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}

try {
m1.t.join();
m2.t.join();
m3.t.join();
m4.t.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main thread exiting .. ");
}

Output:

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

3.5 Thread priorities

Each thread in Java will have an associated priority which is an integer value ranging from 1 (minimum) to 10 (maximum). Thread
scheduler will use the thread priorities to determine the execution schedule of threads. Higher priority threads get the CPU much faster
than the lower priority threads. If two threads have the same priority, the thread scheduler treats them equally and serves them based
on First Come First Serve (FCFS) basis.

setPriority(int) and getPriority()

Thread class defines two methods, one for setting the thread priority and the other for returning the current priority of a thread. Their
signatures are as follows:

void setPriority(int); sets the priority of a calling thread to the one passed as an argument.
int getPriority(); returns the current priority of the calling thread

Priority range

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Thread priority is an integer value ranging from 1 to 10. Thread class defines three integer constants to represent this:

Priority value Integer Constant Description


1 Thread.MIN_PRIORITY Minimum priority of a thread
5 Thread.NORM_PRIORITY Default priority of a thread
10 Thread.MAX_PRIORITY Maximum priority of a thread

Example:

class MyThread implements Runnable {


Thread t;
int count=0;
MyThread(String name, int pri) {
t = new Thread(this, name);
t.setPriority(pri);
t.start();
}
public void run() {
while (true) {
count++;
}
}
}

public class Test {


public static void main(String arg[]) {
// Runnable Object
MyThread m1 = new MyThread("LowPriorityThread", Thread.MIN_PRIORITY);
MyThread m2 = new MyThread("HighPriorityThread", Thread.MAX_PRIORITY);

try {
Thread.sleep(10000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Low priority thread's execution count ..
"+m1.count);
System.out.println("High priority thread's execution count ..
"+m2.count);
}
}

Output:

As you can see, for the duration of 10 seconds the high priority thread has been given more CPU cycles compared to the low priority
thread.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
3.6 Synchronization

Definition

Whenever two or more threads accesses the shared resources we need some mechanism to make sure that only one thread is given
access to the shared resource at any point of time. The process by which this is achieved is called synchronization.

This is to avoid the following problems:

 Visibility problem: It occurs if thread A reads shared data and thread B later changes this data and the thread A is unaware of
this change.
 Access problem: It occurs if several threads tries to access and share the same shared data at the same time.

How synchronization works

The block of code or in general any resources, which is shared among more than two threads and which needs to be synchronized, is
called a monitor (also known as semaphore). Only one thread can access the monitor at any point of time. When a thread enters the
monitor, we say that the thread has acquired the lock, and it prevents any other threads entering into the same monitor until it releases
the lock by exiting the monitor.

Problem demonstration

Below program has a class named Utility which defines a method called printMessage(String). It takes a string argument and prints it
within the flower braces { and }. When two threads accesses this method at the same time each one passing a different string
argument, the order in which these messages are printed are not jumbled (mixed up).

class Utility {
// this is the shared resource
public void printMessage(String msg) {
System.out.print("{");
System.out.print(msg);
System.out.println("}");
}
}

class MyThread implements Runnable {


Thread t;
Utility util;
String msg;
MyThread(Utility util, String msg) {
t = new Thread(this);
this.util = util;
this.msg = msg;
t.start();
}
public void run() {
util.printMessage(msg);
}
}

public class Example {


public static void main(String arg[]) {
Utility util = new Utility();
MyThread m1 = new MyThread(util, "Sachin");
MyThread m2 = new MyThread(util, "Kohli");

}
}
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

Output

Synchronization in Java can be achieved in two different ways:

1. Using synchronized methods


2. Using synchronized blocks

Synchronized methods

This solution is simple. Just prefix the keyword 'synchronized' to the shared resource which needs to be
synchronized. The resource can be a method, variable or any other program elements. Here the shared resource is
the printMessage() method.

class Utility {
// shared resource is synchronized
synchronized public void printMessage(String msg) {
System.out.print("{");
System.out.print(msg);
System.out.println("}");
}
}

class MyThread implements Runnable {


Thread t;
Utility util;
String msg;
MyThread(Utility util, String msg) {
t = new Thread(this);
this.util = util;
this.msg = msg;
t.start();
}
public void run() {
util.printMessage(msg);
}
}

public class Example {


public static void main(String arg[]) {
Utility util = new Utility();
MyThread m1 = new MyThread(util, "Sachin");
MyThread m2 = new MyThread(util, "Kohli");

}
}

Output

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

Synchronized blocks

The solution described above is simple and accepted as long as you have the access to Utility class so that you can
modify it and add synchronized keyword. But, what if you are not the owner of Utility class? Meaning, you are not
authorized to modify the class and you cannot add the synchronized keyword to its method.

In these situations, you can go with synchronized blocks. Simply put calls to the methods defined by this class inside
a synchronized block. This is the general form of the synchronized statement:

synchronized(object) {
// statements to be synchronized
}

Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method
that is a member of object occurs only after the current thread has successfully entered object’s monitor.

class Utility {
public void printMessage(String msg) {
System.out.print("{");
System.out.print(msg);
System.out.println("}");
}
}

class MyThread implements Runnable {


Thread t;
Utility util;
String msg;

MyThread(Utility util, String msg) {


t = new Thread(this);
this.util = util;
this.msg = msg;
t.start();
}

public void run() {


synchronized (util) {
util.printMessage(msg);
}
}
}

public class Test {


public static void main(String arg[]) {
Utility util = new Utility();
MyThread m1 = new MyThread(util, "Sachin");
MyThread m2 = new MyThread(util, "Kohli");
}
}

Output

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

3.7 Inter thread communication


There are three methods defined in Object class namely notify(), notifyAll(), and wait() that constitutes for inter thread
communication.

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 can be called only within a synchronized context.

3.8 Producer Consumer Implementation

Below example shows an implementation of solution for producer-consumer problem.


It consists of four classes.
1. Class Q, the queue you are trying to synchronize.
2. Producer, threaded object that is producing queue entries.
3. Consumer, threaded object that is consuming queue entries.
4. PC, tiny class that creates single Q, Producer, and Consumer.

class Q {
int n;
boolean valueSet = false;

synchronized int get() {


while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
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;
valueSet = 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 = 0;
while (true) {
q.put(i++);
}
}
}

class Consumer implements Runnable {


Q q;

Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}

public void run() {


while (true) {
q.get();
}
}
}

public class PCFixed {


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:

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

3.9 Different states of a Thread

Below figure shows the various states of a thread and its life cycle starting from New state to Terminated state.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

EVENT HANDLING IN JAVA

3.10 Delegation Event Model

Delegation Event Model constitutes of three entities: event, source, and listener.

Event

Event is an object that describes the state change. These objects are encapsulated in a class hierarchy rooted at
java.util.EventObject. An event is propagated from a "Source" object to a "Listener" object by invoking a method on the listener
and passing in the instance of the event subclass which defines the event type generated.

Source

An Event Source is an object which originates or "fires" events. (Example, an Applet). A source must register listeners in order for the
listeners to receive notifications about a specific type of event.

Registering a listener:

Each type of event has its own registration method. Here is the general form:

public void addTypeListener(TypeListener el)

Here, Type is the name of the event, and el is a reference to the event listener. For example, the method
that registers a keyboard event listener is called addKeyListener(). The method that registers a mouse
motion listener is called addMouseMotionListener().

Unregistering a listener:

A source must also provide a method that allows a listener to unregister an interest in a specific type of
event. The general form of such a method is this:

public void removeTypeListener(TypeListener el)

Here, Type is the name of the event, and el is a reference to the event listener. For example,
to remove a keyboard listener, you would call removeKeyListener( ).

Listener

A listener is an object which will be notified when an event occurs. A Listener is an object that implements a specific EventListener
interface extended from the generic java.util.EventListener.

It has two major requirements:

 First, it must have been registered with one or more sources to receive notifications about specific types of events.
 Second, it must implement methods to receive and process these notifications

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

3.11 Event

Almost for every possible type of event that can occur (Ex, click a button, scroll the mouse, etc), Java defines a separate class for it.
java.util.EventObject is the root of all the event classes. The class java.awt.AWTEvent, is a subclass of EventObject. It is the
superclass (either directly or indirectly) of all AWT-based events used by the delegation event model.

The package java.awt.event defines various event classes to describe the events generated by various user interface elements.
Here are the few:

Event class Description


ActionEvent Generated when a button is pressed, a list item is
double-clicked, or a menu
item is selected
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved,
resized, or becomes visible
ContainerEvent Generated when a component is added to or removed
from a container.
FocusEvent Generated when a component gains or loses keyboard
focus.
InputEvent Abstract superclass for all component input event
classes.
ItemEvent Generated when a check box or list item is clicked; also
occurs when a choice
selection is made or a checkable menu item is selected
or deselected.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked,
pressed, or released;
also generated when the mouse enters or exits a
component.
MouseWheelEvent Generated when the mouse wheel is moved.
TextEvent Generated when the value of a text area or text field is
changed.
WindowEvent Generated when a window is activated, closed,
deactivated, deiconified,
iconified, opened, or quit.

Let's explore only KeyEvent and MouseEvent classes

KeyEvent

A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified by these integer
constants:

 KEY_PRESSED
 KEY_RELEASED, and
 KEY_TYPED.

The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated.
Remember, not all key presses result in characters. For example, pressing SHIFT does not generate a character.

There are many other integer constants that are defined by KeyEvent.
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
For example,
 VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters.
 Here are some others:
VK_ALT VK_DOWN VK_LEFT VK_RIGHT
VK_CANCEL VK_ENTER VK_PAGE_DOWN VK_SHIFT
VK_CONTROL VK_ESCAPE VK_PAGE_UP VK_UP

The KeyEvent class defines several methods, but the most commonly used ones are getKeyChar( ), which returns the character that
was entered, and getKeyCode( ), which returns the key code. Their general forms are shown here:

char getKeyChar( )
int getKeyCode( )

MouseEvent

There are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them:

MOUSE_CLICKED The user clicked the mouse.


MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved.

Two commonly used methods in this class are getX( ) and getY( ). These returns the X and Y coordinate of the mouse within the
component when the event occurred. Their forms are shown here:

int getX()
int getY()

3.12 Event Source

Table below lists some of the user interface components that can generate the events described in the previous section.

Event Source Description


Button Generates action events when the button is pressed.
Check box Generates item events when the check box is selected or deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked; generates
item
Menu Item events when an item is selected or deselected.
Scroll bar Generates action events when a menu item is selected; generates item
Text components events when a checkable menu item is selected or deselected.
Window Generates adjustment events when the scroll bar is manipulated.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
3.13 Event Listener

Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. When an event occurs,
the event source invokes the appropriate method defined by the listener and provides an event object as its argument. Table below lists
commonly used listener interfaces and provides a brief description of the methods that they define.

Listener Interface Description


ActionListener Defines one method to receive action events.
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is hidden,
ContainerListener moved, resized, or shown.
FocusListener Defines two methods to recognize when a component is added to
ItemListener or removed from a container.
KeyListener Defines two methods to recognize when a component gains or loses
MouseListener keyboard focus.
MouseMotionListener Defines one method to recognize when the state of an item changes.
MouseWheelListener Defines three methods to recognize when a key is pressed, released,
TextListener or typed.
WindowFocusListener Defines five methods to recognize when the mouse is clicked, enters
WindowListener a component, exits a component, is pressed, or is released.

KeyListener interface

This interface defines following methods


void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

MouseListener interface

This interface defines following methods


void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

MouseMotionListener interface

This interface defines following methods


void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)

3.14 Example programs

Handling Mouse Events

To handle mouse events, you must implement the MouseListener and the MouseMotionListener interfaces. The following applet
demonstrates the process.
o It displays the current coordinates of the mouse in the applet’s status window.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
o Each time a button is pressed, the word “Down” is displayed at the location of the mouse pointer. Each time the
button is released, the word “Up” is shown.
o If a button is clicked, the message “Mouse clicked” is displayed in the upper left corner of the applet display area.
o As the mouse enters or exits the applet window, a message is displayed in the upper-left corner of the applet display
area.
o When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is dragged.

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

public class MouseEventExample extends Applet implements MouseListener, MouseMotionListener {


String msg = "";
int mouseX = 0, mouseY = 0;

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}

// Handle mouse entered.


public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}

// Handle mouse exited.


public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}

// Handle button pressed.


public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}

// Handle button released.


public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
}

// Handle mouse dragged.


public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}

// Handle mouse moved.


public void mouseMoved(MouseEvent me) {
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}

// Display msg in applet window at current X,Y location.


public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}

Output:

Handling Keyboard Events

To handle key board events, you will be implementing KeyListener interface. Before going to the program, Let's see how key events are
generated.
o When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed() event
handler.
o When the key is released, a KEY_RELEASED event is generated and the keyReleased( ) handler is executed.
o If a character is generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( ) handler is
invoked.
Thus, each time the user presses a key, at least two and often three events are generated.
Here is the program to demonstrate the handling of key events.

import java.awt.*;
import java.awt.event.*;

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
import java.applet.*;

public class KeyEventExample extends Applet implements KeyListener {


String msg = "";
int X = 10, Y = 20;

public void init() {


addKeyListener(this);
}

public void keyPressed(KeyEvent ke) {


showStatus("Key Down");
}

public void keyReleased(KeyEvent ke) {


showStatus("Key Up");
}

public void keyTyped(KeyEvent ke) {


msg += ke.getKeyChar();
repaint();
}

public void paint(Graphics g) {


g.drawString(msg, X, Y);
}
}

Output

3.15 Adaptor Classes


Java provides a special feature, called an adapter class, which can simplify the creation of event handlers.

Definition

An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you
want to receive and process ONLY some of the events that are handled by a particular event listener interface. You can define a new

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are
interested.

Table below shows Commonly Used Listener Interfaces Implemented by Adapter Classes.

Adaptor class Listener Interface


ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
MouseAdapter KeyListener
MouseMotionAdapter MouseListener
WindowAdapter MouseMotionListener

Example for Adaptor class

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

public class AdapterDemo extends Applet {


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

class MyMouseAdapter extends MouseAdapter {


AdapterDemo adapterDemo;

public MyMouseAdapter(AdapterDemo adapterDemo) {


this.adapterDemo = adapterDemo;
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}

class MyMouseMotionAdapter extends MouseMotionAdapter {


AdapterDemo adapterDemo;

public MyMouseMotionAdapter(AdapterDemo adapterDemo) {


this.adapterDemo = adapterDemo;
}

// Handle mouse dragged.


public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
}

3.16 Inner Classes, Anonymous Inner Classes

We can handle events in an applet by using three different methods:


By using “this” reference
By using inner classes
By using anonymous inner classes

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

Till now we have seen how to handle events by using “this” reference.

Inner classes

Below example shows how to handle the events by using an inner class.

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

public class InnerClassDemo extends Applet {


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

class MyMouseAdapter extends MouseAdapter {


public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
}
}

Advantage of handling the event by using inner class is that, the inner class can directly call the showStatus() method, and there is no
need to store a reference to the applet.

Anonymous Inner classes

An anonymous inner class is one that is not assigned a name. This example illustrates how to use anonymous inner class to handle
events.

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

public class AnonymousInnerClassDemo extends Applet {


public void init() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
});
}
}

The syntax new MouseAdapter( ) { ... } indicates to the compiler that the code between the braces defines an anonymous inner class.
Furthermore, that class extends MouseAdapter. This new class is not named, but it is automatically instantiated when this expression is
executed.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com

S-ar putea să vă placă și