oops using java (Unit-IV)
oops using java (Unit-IV)
UNIT IV
Multithreaded Programming
➢ A multithreaded program contains two or more parts that can run concurrently.
➢ Each part of such a program is called a thread, and each thread defines a separate
path of execution.
➢ A thread introduces Asynchronous behaviour.
Multitasking
Two types:
1. Process based multitasking
2. Thread based multitasking
Programs requires separate address spaces Same address space is shared by threads.
Interprocess communication is expensive and Interthread communication is inexpensive.
limited.
Context switching from one process to Context switching from one thread to the next
another is also costly. is lower in cost.
May create more idle time. Reduces the idle time.
Ex: Running a Java compiler and Ex: We can format a text using a Text editor
downloading a file from a web site at the and printing the data at the same time.
same time
Method Meaning
getName() Obtain a thread’s name.
getPriority() Obtain a thread’s priority.
setName() Give a name to a thread
setPriority() Set the priority to a thread
isAlive() Determine if a thread is still running.
Join() Wait for a thread to terminate.
Run() Entry point for the thread.
Sleep() Suspend a thread for a period of time.
Start() Start a thread by calling its run method.
currentThread() returns a reference to the thread in which it is called
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
Output:
Thread Group:
A thread group is a data structure that controls the state of a collection of threads as a whole.
Thread Priorities
1) Every thread has a priority that helps the operating system to determine the order in
which threads are scheduled for execution.
2) Thread priorities are integers that ranges between, 1 to 10.
MIN-PRIORITY (a constant of 1)
3) By default every thread is given a NORM-PRIORITY(5). The main thread always have
NORM-PRIORITY.
4) Thread’s priority is used in Context Switch.
Context Switch
Switching from one running thread to the next thread is called as Context Switch.
Rules for Context Switch
1) A thread can voluntarily relinquish control: This is done by explicitly yielding,
sleeping, or blocking on pending I/O. In this scenario, all other threads are examined,
and the highest-priority thread that is ready to run is given the CPU.
Example:
class ThreadDemo implements Runnable
{
public void run()
{
try
{
for(int i=0;i<3;i++)
{
System.out.println("Thread
Demo:"+Thread.currentThread().getName());
Thread.currentThread().sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println("Thread interrupted");
}
}
}
class MultiThreadDemo{
public static void main(String ar[])
{
ThreadDemo r = new ThreadDemo();
Thread t1 = new Thread(r);
t1.setName("First Thread");
t1.setPriority(2);
t1.start();
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
We can obtain the current state of a thread by calling the getState( ) method defined by Thread.
Thread.State getState( )
Synchronizing code
We can synchronize the code in two ways:
1. Using synchronized methods
synchronized void test( )
{
}
2.Using Synchronized statements (synchronized blocks)
synchronized statement
synchronized(objRef) {
// statements to be synchronized
}
Here, objRef is a reference to the object being synchronized
class Account {
private int balance = 50;
public int getBalance()
System.out.println(Thread.currentThread().getName()+ "
completes the withdrawal");
}
else {
Output
wait( ) - wait( ) tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ) or notifyAll( ).
notify( ) - notify( ) wakes up a thread that called wait( ) on the same object.
notifyAll( ) - notifyAll( ) wakes up all the threads that called wait( ) on the same object. One
of the threads will be granted access.
Producer produces an item and consumer consumes an item produced by the producer
immediately. Producer should not produce any item until the consumer consumes the item.
Consumer should wait until producer produces a new item.
class Q
{
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
}
catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
class PC
{
public static void main(String args[])
{
Q q = new Q();
Producer p = new Producer(q);
Consumer c = new Consumer(q);
}
}
Example:
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
Example
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 3; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
synchronized(this) {
try {
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
System.out.println("Resuming thread One");
ob2.mysuspend();
Byte Streams
Byte streams provide a convenient means for handling input and output of bytes. Byte
streams are used, for example, when reading or writing binary data.
Character Streams
Character streams provide a convenient means for handling input and output of
characters. They use Unicode and, therefore, can be internationalized. Also, in some
cases, character streams are more efficient than byte streams.
Character streams are defined by using two class hierarchies. At the top are two
abstract classes: Reader and Writer. These abstract classes handle Unicode character
streams.
Example
➢ applets are small applications that are accessed on an Internet server, transported over the
Internet, automatically installed, and executed by Java compatible web browser or
appletviewer.
AppletSkel.java
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start() {
// start or resume execution
System.out.println("START");
}
RunApplet.html
Enumerations
a) An enumeration is a list of named constants.
b) Java enumerations are class types.
c) Each enumeration constant is an object of its enumeration type.
d) Each enumeration constant has its own copy of any instance variables defined by the
enumeration.
e) All enumerations automatically inherit one: java.lang.Enum.
// An enumeration of apple varieties.
enum Apple {
A, B, C, D, E
}
➢ The identifiers Jonathan, GoldenDel, and so on, are called enumeration constants.
➢ Each is implicitly declared as a public, static, final member of Apple.
➢ In the language of Java, these constants are called self-typed.
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.
Enum Example:
class EnumDemo {
public static void main(String args[]) {
Apple ap;
System.out.println("Here are all Apple constants:");
// use values()
Apple allapples[] = Apple.values();
for(Apple a : allapples)
System.out.println(a);
System.out.println();
// use valueOf()
ap = Apple.valueOf("Winesap");
System.out.println("ap contains " + ap);
}
}
enum Apple {
A(10), B(9), C(12), D(15), E(8);
class EnumConsDemo {
public static void main(String args[]) {
Apple ap;
// Display price of B.
System.out.println("B costs " + Apple.B.getPrice() + " cents.\n");
➔ Type wrappers are classes that encapsulate a primitive type within an object.
➔ The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and
Boolean.
➔ Type wrappers are related directly to auto-boxing / auto-unboxing feature.
Autoboxing
Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into
its equivalent type wrapper.
Autounboxing
Auto-unboxing is the process by which the value of a boxed object is automatically extracted
(unboxed) from a type wrapper.
Autoboxing/Autounboxing- benefits
1) In assignments
2) In Method arguments and return types
3) In Expressions
4) In switch statement and any loop statements
1) Autoboxing in assignments
2) Autoboxing in Methods
int m(Integer v) {
return v ; // auto-unbox to int
}
3) Autoboxing in expressions
Integer iOb = 2;
switch(iOb) {
case 1: System.out.println("one");
break;
case 2: System.out.println("two");
break;
default: System.out.println("error");
}
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.
@Override
@SuppressWarnings
@Deprecated
1) @Override
@Override annotation assures that the subclass method is overriding the parent
class method. If it is not so, compile time error occurs.
2) Deprecated
3) SuppressWarnings
@Target
@Retention
@Inherited
@Documented
1) @Target
2) @Retention
3) @Inherited
@Inherited annotation indicates that the annotation type can be inherited from the
super class.
4) @Documented
class Animal{
void eat(){
System.out.println("eating something");
}
}
@interface MyAnnotation
{
}
Types of Annotation
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation
1) Marker Annotation
@interface MyAnnotation{ }
2) Single-value annotation
For example:
@interface MyAnnotation{
int value() default 0;
}
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();
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation{
int value();
}
//Applying annotation
class Hello{
@MyAnnotation(value=10)
public void sayHello(){
System.out.println("hello annotation");
}
}
//Accessing annotation
class TestCustomAnnotation{
public static void main(String args[])throws Exception{
MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
System.out.println("value is: "+manno.value());
}
}
Generics
➔ Generics are called as parameterized types.
➔ The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
➔ Generics can be applied to a class, interface or a method.
➔ Generics Work Only with Reference Types.
1) Type-safety:
We can hold only a single type of objects in generics. It doesn’t allow to store other
objects.
2) Compile-Time Checking:
It is checked at compile time so problem will not occur at runtime. The good
programming strategy says it is far better to handle the problem at compile time than runtime.
Generic class
A class that can refer to any type is known as generic class. Here, we are using T type
parameter to create the generic class of specific type.
class MyGen<T>{
T obj;
void add(T obj){
this.obj=obj;
Generic Method
Like generic class, we can create generic method that can accept any type of argument.