Threads Last Chapters
Threads Last Chapters
•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:
3) notifyAll() method
Syntax:
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);
Output :
going to withdraw
deposite completed
withdraw is completed
----------------------------------------------
class Q
{
int n;
boolean valueSet=false;
{
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();
{
Q q; Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}
{
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.
group.
}
}
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.
The java.lang.Thread class provides two methods for java daemon thread.
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.
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
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.
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
@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.
import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
list.add("abc");
list.add("def");
list.add("ghi");
for(Object obj:list)
System.out.println(obj);
}}
@Deprecated
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
1) Marker Annotation
@interface MyAnnotation{}
2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
@interface MyAnnotation{
int value();
@interface MyAnnotation{
}
JAVA PROGRAMMING CHAPTER 7: Multithreading PAGE NO140
@MyAnnotation(value=10)
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();
@interface MyAnnotation{
@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:
// A Simple Java program to show working of user defined Generic classes and Geneic
function
class Test<T> {
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);} }
-----------------------------------------------------