0% found this document useful (0 votes)
17 views19 pages

Threads Last Chapters

Uploaded by

prasaddurga6527
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views19 pages

Threads Last Chapters

Uploaded by

prasaddurga6527
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO 125

Inter Thread Communication


Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused


running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed. It is implemented by following methods of Object class:

•wait()

•notify()

•notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.

2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation. Syntax:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

Syntax:

public final void notifyAll()


JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO126

Example for Inter Thread Communication

class Customer {
int amount=10000;
synchronized void withdraw(int amount) {
System.out.println("going to withdraw");
if(this.amount<amount) {
System.out.println("insuffient funds,waiting for deposit");
try {
wait();
}
catch(Exception e)
{
System.out.println("error"+e);
}
}
this.amount=this.amount-amount;
System.out.println("withdraw is completed");
System.out.println("remaining balance amount:"+this.amount);

synchronized void deposit(int amount) {


System.out.println("going to deposit amount");
this.amount=this.amount+amount;
System.out.println("deposite completed");
System.out.println("balance after deposit:"+this.amount);
notify();
}
}
public class interthread {
public static void main(String args[])
{
final Customer c=new Customer();
new Thread() {
public void run() {
c.withdraw(15000);
}
}.start();
new Thread() {
public void run() {
c.deposit(10000);
}
}.start();
}
}
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO 127

Output :

going to withdraw

insuffient funds, waiting for deposit

going to deposit amount

deposite completed

balance after deposit:20000

withdraw is completed

remaining balance amount:5000

----------------------------------------------

*****Aim: Write a Java program that correctly implements the producer


consumer problem using the concept of inter thread communication.
Program:

class Q

{
int n;

boolean valueSet=false;

synchronized int get()

{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;

}
synchronized void put(int n)
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO128

{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception 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()
{
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO 129

while(true)
{
q.get();
}
}
}
class ProdCons
{
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:

-----------------------------------------------------------------------------
Thread Groups:
 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


JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO130

Creates a thread group with


1) ThreadGroup(String name)
given name.

Creates a thread group with a


2) ThreadGroup(ThreadGroup parent, String name)
given parent group and name.

Methods of ThreadGroup class

.N Modifier Method Description


. and Type

This method determines if the currently


1) void checkAccess() running thread has permission to modify the
thread group.

This method returns an estimate of the


2) int activeCount() number of active threads in the thread group
and its subgroups.

This method returns an estimate of the


3) int activeGroupCount() number of active groups in the thread group
and its subgroups.

This method destroys the thread group and


4) void destroy()
all of its subgroups.

This method copies into the specified array


5) int enumerate(Thread[] list) every active thread in the thread group and
its subgroups.

This method returns the maximum priority


6) int getMaxPriority()
of the thread group.

This method returns the name of the thread


7) String getName()
group.

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


JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO 131

group.

This method interrupts all threads in the


9) void interrupt()
thread group.

This method tests if the thread group is a


10) boolean isDaemon()
daemon thread group.

setDaemon(boolean This method changes the daemon status of


11) void
daemon) the thread group.

This method tests if this thread group has


12) boolean isDestroyed()
been destroyed.

This method prints information about the


13) void list()
thread group to the standard output.

This method tests if the thread group is


14) boolean parentOf(ThreadGroup g) either the thread group argument or one of
its ancestor thread groups.

This method is used to suspend all threads in


15) void suspend()
the thread group.

This method is used to resume all threads in


16) void resume() the thread group which was suspended using
suspend() method.

This method sets the maximum priority of


17) void setMaxPriority(int pri)
the group.

This method is used to stop all threads in the


18) void stop()
thread group.

This method returns a string representation


19) String toString()
of the Thread group.
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO132

Program to demonstrate ThreadGroup

public class ThreadGroupDemo implements Runnable


{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args)
{
ThreadGroupDemo obj = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("ParentThreadGroup");

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


t1.start();
Thread t2 = new Thread(tg1, obj,"two");
t2.start();
Thread t3 = new Thread(tg1, obj,"three");
t3.start();
System.out.println("Thread Group Name: "+tg1.getName());
tg1.list(); //give information of thread group tg1
int x=tg1.activeCount();
System.out.println("number of active threads in thread group are"+x);
System.out.println(tg1.getParent());
System.out.println(tg1.isDaemon());
tg1.setDaemon(true);
System.out.println(tg1.isDaemon());
System.out.println(tg1.toString());
tg1.stop();

}
}
Output:
Thread Group Name: ParentThreadGroup
three
two
one
java.lang.ThreadGroup[name=ParentThreadGroup,maxpri=10]
Thread[one,5,ParentThreadGroup]
Thread[two,5,ParentThreadGroup]
Thread[three,5,ParentThreadGroup]
number of active threads in thread group are2
java.lang.ThreadGroup[name=main,maxpri=10]
false
true
java.lang.ThreadGroup[name=ParentThreadGroup,maxpri=10]
----------------------------------------------------------------------------------------------------------------

Daemon thread
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO 133

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.

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.

Methods for Java Daemon thread by Thread class

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

No. Method Description

is used to mark the current thread as


1) public void setDaemon(boolean status)
daemon thread or user thread.

is used to check that current is


2) public boolean isDaemon()
daemon.

Program to Demonstrate Daemon Thread:

public class DaemonDemo 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){
DaemonDemo t1=new DaemonDemo();//creating thread
DaemonDemo t2=new DaemonDemo();
DaemonDemo t3=new DaemonDemo();

t1.setDaemon(true);//now t1 is daemon thread


t1.start();//starting threads
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO134

t2.start();
t3.start();
}
}
Output:
daemon thread work
user thread work
user thread work
-------------------------------------------------------------------------------------------------------
Enumeration
Enumeration is created using the enum keyword
Syntax for defining Enumeration:

enum enumerationtype{identifier,identifier2,…….}

Example:
enum Season { WINTER, SPRING, SUMMER, FALL }
enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY}
note:
 enum can be defined outside or inside of the class.
 The identifiers are called as enumeration constants or self -typed
 The identifier is implicitly declared as public ,static final members if enumeration
type
 However, even though enumerations define a class type, you do not instantiate an
enum using new keyword. Instead, enumeration variable are declared in same way
as you do one of the primitive types.
Syntax for declaring Enumeration variable:

enumerationtype variablename1,variablename2,…..;

Example:
Season s;
Day d;

Note:
enumeration variable can accept only enumeration constant as its value.
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO 135

s= Season. WINTER;
d= Day. SUNDAY
Initializing specific value to the enum constants:

The enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can
initialize the specific value to the enum constants by defining fields and constructors. As
specified earlier, Enum can have fields, constructors and methods.

enum Season{ WINTER(5), SPRING(10), SUMMER(15), FALL(20)};

The values( ) and valueOf( ) Methods


All enumerations automatically contain two predefined methods: values( ) and valueOf( ).
Their general forms are shown here:

public static enum-type[ ] values( );


public static enum-type valueOf(String str);

The values( ) method returns an array that contains a list of the enumeration constants.
The valueOf( ) method returns the enumeration constant whose value corresponds to the
string passed in str.
Example on Enumeration
// Use the built-in enumeration methods.
// An enumeration of apple varieties.
enum Season { WINTER, SPRING, SUMMER, FALL }
class EnumDemo2 {
public static void main(String args[])
{
Season s;
// use values()
Season allseasons[] = Season.values();
for(Season s : allseasons)
System.out.println(s);
System.out.println();
// use valueOf()
s = Season.valueOf("SUMMER");
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO136

System.out.println("s contains " + s);


}
}

Output:

WINTER
SPRING
SUMMER
FALL
s contains SUMMER
-----------------------------------------------------------------------------------------------------------------------------
Auto boxing & Un boxing

The automatic conversion of primitive data types into its equivalent Wrapper type is known
as boxing and opposite operation is known as un boxing.
This is the new feature of Java5. So java programmer doesn't need to write the conversion
code.

Advantage of Auto boxing and Un boxing:


No need of conversion between primitives and Wrappers manually so less coding is
required.

Simple Example of Autoboxing in java

class BoxingDemo {
public static void main(String args[]) {
int a=50;
Integer a2=new Integer(a);//Boxing

Integer a3=5;//Boxing

System.out.println(a2+" "+a3);
}
}
Output:
50 5
Unboxing: The automatic conversion of wrapper class type into corresponding primitive
type, is known as Unboxing. Let's see the example of unboxing
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO 137

class UnboxingDemo {
public static void main(String args[]) {
Integer i=new Integer(50);
int a=i;
System.out.println(a);
}
}
Output:
50
------------------------------------------------------------------------------------------------
Java Annotations
Java Annotation is a tag that represents the metadata i.e. attached with class, interface,
methods or fields to indicate some additional information which can be used by java compiler
and JVM.
Built-In Java Annotations
There are several built-in annotations in Java. Some annotations are applied to Java code and
some to other annotations.
Built-In Java Annotations used in Java code
@Override
@SuppressWarnings
@Deprecated

@Override
@Override annotation assures that the subclass method is overriding the parent class method.
If it is not so, compile time error occurs.
Sometimes, we do the silly mistake such as spelling mistakes etc. So, it is better to mark
@Override annotation that provides assurity that method is overridden.

class Animal
{
void eatSomething()
{
System.out.println("eating something");
}
}
class Dog extends Animal
{
@Override
void eatSomething()
{System.out.println("eating foods");}//should be eatSomething
}
class TestAnnotation1{
public static void main(String args[]){
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO138

Animal a=new Dog();//upcasting


a.eatSomething();
}}
Output:
eating foods

@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.

import java.util.*;

class TestAnnotation2{

@SuppressWarnings("unchecked")

public static void main(String args[]){

ArrayList list=new ArrayList();

list.add("abc");

list.add("def");

list.add("ghi");

for(Object obj:list)

System.out.println(obj);

}}

@Deprecated

@Deprecated annoation marks that this method is deprecated so compiler prints


warning. It informs user that it may be removed in the future versions. So, it is better not to
use such methods.

class A{
void m(){System.out.println("hello m");}

@Deprecated
void n(){System.out.println("hello n");}
}

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

A a=new A();
a.n();
}}
output:
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO 139

hello n

Java Custom Annotations or Java User-defined annotations


Java Custom annotations or Java User-defined annotations are easy to create and use.
The @interface element is used to declare an annotation. For example:
@interface MyAnnotation{}

Here, MyAnnotation is the custom annotation name.

Points to remember for java custom annotation signature

There are few points that should be remembered by the programmer

 Method should not have any throws clauses


 Method should return one of the following: primitive data types, String, Class, enum
or array of these data types.
 Method should not have any parameter.
 We should attach @ just before interface keyword to define annotation.
 It may assign a default value to the method.
Types of Annotation
There are three types of annotations.
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation

1) Marker Annotation

An annotation that has no method, is called marker annotation. For example:

@interface MyAnnotation{}

The @Override and @Deprecated are marker annotations.

2) Single-Value Annotation

An annotation that has one method, is called single-value annotation. For example:

@interface MyAnnotation{

int value();

We can provide the default value also. For example:

@interface MyAnnotation{

int value() default 0;

}
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO140

Let's see the code to apply the single value annotation.

@MyAnnotation(value=10)

The value can be anything.

3) Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation.

For example:

@interface MyAnnotation

int value1();

String value2();

String value3();

We can provide the default value also. For example:

@interface MyAnnotation{

int value1() default 1;

String value2() default "";

String value3() default "xyz";

Let's see the code to apply the multi-value annotation.

@MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")

----------------------------------------------------------------------------------
Generics:

Generics
Introduction of Generics:
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO 141

Generics mean parameterized types. Parameterized types are important because they enable
you to create classes, interfaces, and methods in which the type of data upon which they
operate is specified as a parameter. Using generics, it is possible to create a single class, for

example, that automatically works with different types of data. A class, interface, or method
that operates on a parameterized type is called generic, as in generic class or generic method .
The General Form of a Generic Class
Syntax for declaring a generic class:

class class-name<type-param-list> { // ...


syntax for declaring a reference to a generic class:

class-name<type-arg-list> var-name =new class-name<type-arg-list>(cons-arg-list);

Note: In Parameter type we cannot use primitives like 'int','char' or 'double'.


Generic Functions:
We can also write generic functions that can be called with different types of arguments
based on the type of arguments passed to generic method, the compiler handles each
method.

// A Simple Java program to show working of user defined Generic classes and Geneic
function
class Test<T> {

T obj; // An object of type T is declared


Test(T obj) // constructor {
this.obj = obj;
}
public T getObject() {
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO142

Advantages of Generics:
Programs that uses Generics has got many benefits over non-generic code.
1. Code Reuse: We can write a method/class/interface once and use for any type we
want.
2. Type Safety : Generics make errors to appear compile time than at run time (It’s
always better to know problems in your code at compile time rather than making
your code fail at run time).
3. Individual Type Casting is not needed:
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO 143

If we do not use generics, then, we need to type cast each read value. Typecasting at
every retrieval operation is a big headache.
4. Implementing generic algorithms: By using generics, we can implement algorithms
that work on
Different types of objects and at the same they are type safe too.

import java.util.*;
class Test
{
public static void main(String[] args){
// Creating a an ArrayList with String specified
ArrayList <String> al = new ArrayList<String> ();
al.add("Sachin");
al.add("Rahul");
al.add(10); // Now Compiler doesn't allow this
//String s1 = (String)al.get(0); Typecasting is not needed
String s1 = al.get(0);
//String s2 = (String)al.get(1); Typecasting is not needed
String s2 = al.get(1);
String s3 = (String)al.get(2); Typecasting is not needed
String s2 = al.get(2);} }

-----------------------------------------------------

You might also like