Java Unit-3 Student
Java Unit-3 Student
JAVA PROGRAMMING
UNIT III
Thread
• Threads are independent because all the threads follow a separate path
of execution within the program.
• Each thread has its own program counter, stack and local variables.
•Each process has a separate address in memory and switching from one process
to another requires some time for saving and loading registers and updating lists.
•A process is heavy weight and cost of communication between the process is high.
Thread-based multi-tasking (Multithreading)
•Threads share the same address space. A thread is light weight and cost of
communication between the thread is low.
Different between Multitasking and Multithreading
FEATURES MULTITASKING MULTITHREADING
Definition When a single processor does many jobs Multitasking occurs when the CPU does
(program, threads, process, task) at the many tasks, such as a program, process,
same time, it is referred to as task, or thread.
multitasking.
Basic A CPU may perform multiple tasks at Multithreading allows a CPU to generate
once by using the multitasking method. numerous threads from a job and process
them all at the same time.
Resources and The system must assign different The system assigns a single memory
Memory resources and memory to separate block to each process.
programs that are running concurrently in
multitasking.
Switching CPU switches between programs CPU switches between the threads
frequently. frequently.
Speed of Execution It is comparatively slower in execution. It is comparatively faster in execution.
Working A user may easily run several jobs off of A CPU has the ability to split a single
their CPU at once. program into several threads to improve
its functionality and efficiency.
Process The process of terminating a task takes It requires considerably less time to end a
Termination comparatively more time. process.
LIFE CYCLE OF A THREAD
A thread can be in any of the following states:
New
Runnable
Running
Blocked
Waiting
Timed Waiting
Terminated
Explanation
• New: A newly created thread that has not yet started the execution. It
remains in this state until the program starts the thread using start()
method.
• It is also referred to as a born thread.
• Runnable: If a thread is in this state it means that the thread is ready for
execution and waiting for the availability of the processor.
• If all threads in queue are of same priority then they are given time slots for
execution in round robin fashion.
• Running: It means that the processor has given its time to the thread for execution. A
thread keeps running until the following conditions occurs:
(a) Thread give up its control on its own and it can happen in the following situations:
• A thread gets suspended using suspend() method which can only be revived using
resume() method.
• A thread is made to sleep for a specified period of time using sleep(time)
• Timed Waiting: A thread that is waiting for another thread to perform a task for a specified
interval of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
• Terminated: A runnable thread enters the dead or terminated state when it successfully
completes its task or otherwise terminated due to any error or even forcefully killed.
THREAD-LIFE CYCLE
The Main() thread
• When we run any java program, the program begins to execute its code starting from the
main method.
• Therefore, the JVM creates a thread to start executing the code present in main method. This
thread is called as main thread.
• Thread priorities are integers which decide how one thread should be treated with respect to
the others.
• Thread priority decides when to switch from one running thread to another, and the process is
called context switching.
• A thread can voluntarily release control and the highest priority thread that is ready to run is
given the CPU.
• A thread can be preempted by a higher priority thread no matter what the lower priority
thread is doing. Whenever a higher priority thread wants to run it does.
• To set the priority of the thread, setPriority() method is used which is a method of the class
Thread Class.
• In place of defining the priority in integers, we can use MIN_PRIORITY with value 1,
NORM_PRIORITY(Default Priority) with value 5, MAX_PRIORITY with value 10
Get and Set Thread Priority
•There are two types of thread synchronization namely mutual exclusive and
inter- thread communication.
• Mutual Exclusive
Synchronized method.
Synchronized block.
Static synchronization.
by synchronized method
by synchronized block
by static synchronization
Synchronized method:
• If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
• for that object and releases it when the thread completes its task.
Synchronized Block
Definition
• Inter-Thread communication or Co-operation is defined as the
process of allowing synchronized threads to communicate with each
other.
wait()
notify()
notifyAll()
• 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.
Syntax:
public final void wait()throws InterruptedException
public final void wait(long timeout)throws
InterruptedException
• 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.
Syntax: public final void notify()
notifyAll() wakes up all the threads that called wait() on the same
object.
Syntax: public void notifyAll()
Understanding the process of inter-thread communication
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the
lock.
• At the same time, the consumer is consuming the data (i.e. removing
it from the buffer), one piece at a time.
• The java.io package contains all the classes required for input and output operations.
Stream
• A stream can be defined as a sequence of data.
There are two kinds of Streams −
• Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most
frequently used classes are,
• Java byte streams are used to perform input and output of 8-bit bytes, whereas Java Character
streams are used to perform input and output for 16-bit unicode.
• Though there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes
$javac CopyFile.java
$java CopyFile
Standard Streams
•All the programming languages provide support for standard I/O where the user's
program can take input from a keyboard and then produce an output on the
computer screen.
System.out.println("simple message");
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
System.err.println("error message");
Reading and Writing Console
• Reading Console Input:
The preferred method of reading console input is to use a character-oriented
stream.
•There are three different ways for reading input from the user in the command line
environment(console).
1.Using Buffered Reader Class
2.Using Scanner Class
3.Using Console Class
Reading and Writing Console
Reading Console Input:
The preferred method of reading console input is to use a character-oriented
stream.
There are three different ways for reading input from the user in the command
line environment(console).
1.Using Buffered Reader Class
2.Using Scanner Class
3.Using Console Class
1.Using Buffered Reader Class
InputStreamReader(InputStream inputStream)
•Even though System.out is a byte stream, using it for a simple program output is still acceptable.
•Because the PrintStream is an output stream derived from the OutputStream, it also implements the
low-level method write(). Thus, write() can be used to write to the console.
•This method writes the byte specified by byteval. Although byteval is declared as an integer, only
the low-order eight bits are written.
Example
• ByteArrayOutputStream
• DataOutputStream
Example
• Methods inside a generic class can make use of a class’ type parameter and are, therefore,
automatically generic relative to the type parameter.
• However, it is possible to declare a generic method that uses one or more type parameters of its
own.
• The scope of arguments is limited to the method where it is declared. It allows static as well as
non-static methods.
Syntax for a generic method:
<type-parameter> return_type method_name (parameters)
{
...
}
class Demo
{
static <V, T> void display (V v, T t)
{
System.out.println(v.getClass().getName()+" = " +v);
System.out.println(t.getClass().getName()+" = " +t);
}
public static void main(String[] args)
{
display(88," R.M.D Engineering College ");
}
}
Output:
java lang.Integer = 88
java lang.String = R.M.D Engineering College
Example 2
Following example illustrates how we can print an array of different type using a single Generic method
public class GenericMethodTest
{
// generic method printArray
public static < E > void printArray( E[] inputArray )
{
// Display array elements for(E element : inputArray)
{
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String args[]) Output
{ Array integerArray contains:
12345
// Create arrays of Integer, Double and Character Array doubleArray contains:
Integer[] intArray = { 1, 2, 3, 4, 5 }; 1.1 2.2 3.3 4.4
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Array characterArray contains:
RMDEC
Character[] charArray = { 'R', 'M', 'D', 'E', 'C' };
• In Java Generics it is possible to set restriction on the type that will be allowed to pass to a type-parameter. This is
done with the help of extends keyword when specifying the type parameter.
< T extends Number >
• Here we have taken Number class, it can be any wrapper class name. This
• specifies that T can be only be replaced by Number class data itself or any of its subclass.
Example:
• Create a generic class that contains a method that returns the average of an array of numbers.
class Stats<T extends Number>
{
T[] nums; // array of Number or subclass
Stats(T[] o)
{
nums = o;
}
double average()
{
double sum = 0.0;
for(int i=0; i < nums.length; i++) sum += nums[i].doubleValue(); return sum / nums.length;
}
}
public class GenDemo
{
public static void main(String[] args)
{
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums);
double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums);
double w = dob.average();
System.out.println("dob average is " + w);
}
}
Generic Interface
Comparable interface is a great example of Generics in interfaces and it’s written as:
Package
import java.util*;
public interface Comparable<T>
{
public int compareTo(T o);
}
In similar way, we can create generic interfaces in java. We can also have multiple type parameters as in
Map interface. Again we can provide parameterized value to a parameterized type also, for example new
HashMap<String, List<String>>(); is valid.
Restrictions and Limitations
There are a few restrictions that you need to keep in mind when using generics.
They involve creating objects of a type parameter, static members, exceptions, and arrays.
Type Parameters Can’t Be Instantiated
It is not possible to create an instance of a type parameter.
For example, consider this class: class Gen<T>
{
T ob; Gen()
{
ob = new T(); // Illegal!!!
}
}
Here, it is illegal to attempt to create an instance of T. The reason is since T does not exist at run time, how the
compiler doesn’t know what type of object to create.
Restrictions on Static Members
No static member can use a type parameter declared by the enclosing class. For example,both of the static members of this
class Wrong<T>
static T ob;
return ob;
Although we can’t declare static members that use a type parameter declared by the enclosing class, we can declare static