Java Unit IV
Java Unit IV
MULTITHREADING:
Differences between Multiprocessing and Multithreading:
Multiprocessing:
A multiprocessing system has more than two processors. The CPUs are added to the system that
helps to increase the computing speed of the system. Every CPU has its own set of registers and
main memory.
Multithreading:
Multithreading is a program execution technique that allows a single process to have multiple code
segments (like threads|). It is also running concurrently within the “context” of that process.
Parallel Multiple processes are executed Multiple threads are executed in a parallel
Action in a parallel fashion. fashion.
In multiprocessing, many
In multithreading, many threads are executed
Execution processes are executed
simultaneously.
simultaneously.
In multiprocessing, a separate
Address In multithreading, a common address space is
address space is created for each
space used for all the threads.
process.
Multiprocessing requires a
Multithreading requires less time and few
Resources significant amount of time and
resources to create.
large number of resources.
1|Page
2|Page
Thread States and Thread Life Cycle in Java:
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of
the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
The diagram shown below represents various states of a thread at any instant in time.
1. New
Thread state for a thread that has not yet started.
public static final Thread. State NEW
2. Runnable
Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but
it may be waiting for other resources from the operating system such as a processor.
public static final Thread. State RUNNABLE
3. Blocked
Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a
monitor lock to enter a synchronized block/method or re-enter a synchronized block/method after calling
Object.wait().
public static final Thread. State BLOCKED
4. Waiting
Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following
methods:
Object.wait with no timeout
Thread.join with no timeout
LockSupport.park
public static final Thread.State WAITING
5. Timed Waiting
Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state due to
calling one of the following methods with a specified positive waiting time:
Thread.sleep
Object.wait with timeout
Thread.join with timeout
LockSupport.parkNanos
LockSupport.parkUntil
public static final Thread.State TIMED_WAITING
6. Terminated
Thread state for a terminated thread. The thread has completed execution.
3|Page
Declaration: public static final Thread.State TERMINATED
Creating Threads:
A thread is similar to a program that has a single flow control.
We can create a thread in two ways
(1). By extending Thread class
(2). By implementing Runnable interface
Example:
class MyThread extends Thread
{
public void run ()
{
System.out.println(“This is my first thread and it is running”);
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
t1.start();
}
}
Example:
class MyRunnable implements Runnable
{
public void run ()
{
System.out.println(“First thread running”);
}
public static void main(String[] args)
{
MyRunnable r=new MyRunnable();
Thread t1=new Thread(r);
t1.start();
}
}
Output: First thread running
4|Page
Thread Interrupted:
Thread Interruption in Java:
Thread interruption is a mechanism to signal a thread to stop its execution. It's not a forceful
termination but rather a polite request.
Methods:
Handling Interruption:
Thread Priorities:
As we already know java being completely object-oriented works within a multithreading environment in
which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a
thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the
thread or it can be given by the programmer explicitly.
Priorities in threads is a concept where each thread is having a priority which in layman’s language one
can say every object is having priority here which is represented by numbers ranging from 1 to 10.
The default priority is set to 5 as excepted.
Minimum priority is set to 1.
Maximum priority is set to 10.
6|Page
**********
7|Page
Stream based I/O(java.io):
The stream classes-Byte streams and character streams:
Java offers two types of streams:
1.Byte streams.
2.Character streams
1. Byte Streams:
Byte Stream classes are used to read bytes from and write bytes to an input stream. To put it another
way, Byte Stream classes read and write 8-bit data.
Using Byte Stream classes, we can save video, audio, characters, and so on. The java.io package
contains these classes.
Byte Java streams have a three-phase mechanism:
Split: A spliterator divides the input data source into a stream. The Java Spliterator interface is an
internal iterator that divides the stream into smaller parts for traversal.
Apply: The elements in the stream are processed.
Combine: After the elements have been processed, they are combined once more to produce a single
result.
9|Page
In the above example, we first create a File object to represent the file “filename.txt”. Then we create
a FileWriter object to write data to the file. We then use the write() method of the FileWriter object to
write the string “Hello World!” to the file. Finally, we close the FileWriter object using the close()
method.
Method Description
String readLine() It is used to read a single line of text from the console.
String readLine(String fmt, Object... It provides a formatted prompt then reads the single line of
args) text from the console.
char[] readPassword(String fmt, It provides a formatted prompt then reads the password that is
Object... args) not being displayed on the console.
Console format(String fmt, Object... It is used to write a formatted string to the console output
args) stream.
10 | P a g e
11 | P a g e