Documente Academic
Documente Profesional
Documente Cultură
INTRODUCTION:
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved by two ways:
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process have its own address in memory i.e. each process allocates separate
memory area.
Process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.
Cost of communication between the thread is low.
What is Thread in java
A thread is an independent path of execution within a program. Many threads can run
concurrently within a program. Every thread in Java is created and controlled by
the java.lang.Thread class.
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
As shown in the above figure, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one process
can have multiple threads. .At a time one thread is executed only.
Multithreading
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
New
The thread is in new state if we create an instance of Thread class but before the
invocation of start() method.
Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
Running
The thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
Terminated
A thread is in terminated or dead state when its run() method exits.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It
performs following tasks:
A new thread starts (with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
1. By Extending Thread Class
When the class extends a Tread class, it must override run() method of the
Thread class.
Must supply a public void run() method
Start a thread by invoking the start() method
When a thread starts, it executes run()
When run() returns, thread is finished/dead
Syntax:
class classname extends Thread
{
public void run ( ) //must override
{
}
}
public class classname
{
public static void main( String args[])
{
classname objname = new classname ();
objname.start () ;
}
}
Example Program:
class Multi extends Thread
{
Multi(int a) //Parameterized Constructor
{
System.out.println("Result" +a);
}
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi(100);
t1.start();
}
}
Output :
Result 100
Thread is running...
A Thread can be created by extending Thread class also. But Java allows only one class
to extend, it won’t allow multiple inheritance. So it is always better to create a thread
by implementing Runnable interface. Java allows you to implement multiple interfaces
at a time.
By implementing Runnable interface, you need to provide implementation for run()
method.
To run this implementation class, create a Thread object, pass Runnable
implementation class object to its constructor. Call start() method on thread class to
start executing run() method.
Implementing Runnable interface does not create a Thread object, it only defines an
entry point for threads in your object. It allows you to pass the object to the Thread
(Runnable implementation) constructor.
Output:
Thread is running…
If you are not extending the Thread class, your class object would not be treated as a
thread object. So you need to explicitly create Thread class object. We are passing the object of
your class that implements Runnable so that your class run() method may execute.
Sleep method
The sleep() method of Thread class is used to sleep a thread for the specified amount of
time.
Syntax:
sleep()
The Thread class provides two methods for sleeping a thread:
As we know well that at a time only one thread is executed. If we sleep a thread for the
specified time, the thread scheduler picks up another thread and so on.
Output
1
1
2
2
3
3
4
4
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
Synchronization:
At times when more than one thread try to access a shared resource, we need to ensure
that resource will be used by only one thread at a time. The process by which this is achieved is
called synchronization. The synchronization keyword in java creates a block of code referred to
as critical section.(or) Synchronization in java is the capability to control the access of multiple
threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access
the shared resource.
Every Java object with a critical section of code gets a lock associated with the object. To
enter critical section a thread need to obtain the corresponding object's lock.
General Syntax :
Synchronized (object)
{
// statement to be synchronized
}
Here ,object is a reference to the object being synchronized.
Why we use Synchronization ?
The synchronization is mainly used to
If we do not use synchronization, and let two or more threads access a shared resource at
the same time, it will lead to distorted results.
Consider an example, suppose we have two different threads T1 and T2, T1 starts
execution and save certain values in a file temporary.txt which will be used to calculate some
result when T1 returns. Meanwhile, T2 starts and before T1 returns, T2 change the values saved
by T1 in the file temporary.txt (temporary.txt is the shared resource). Now obviously T1 will
return wrong result.
To prevent such problems, synchronization was introduced. With synchronization in
above case, once T1 starts using temporary.txt file, this file will be locked (LOCK mode), and no
other thread will be able to access or modify it until T1 returns.
Types of Synchronization
1.Mutual Exclusive:
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. This can be done by three ways in java:
i. by synchronized method
ii. by synchronized block
iii. by static synchronization
class Table
{
synchronized void printTable(int n)
{ //synchronized method
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
class Table
{
void printTable(int n)
{
synchronized(this)
{ //synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
} //end of the method
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class TestSynchronizedBlock1
{
public static void main(String args[])
{
Table obj = new Table(); //only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
In Java the files are viewed as sequential streams of bytes. Stream itself is sequence of data.when
building program in Java we often need to interact with out side world, i.e files,network streams
etc, Or when we want to store the state of the object we need to interact with these out side world
.
These files are also called binary files. Because when the data is taken as input or shown as
output is in format of binary.For example, if we store the value 6, it would be stored in the binary
format of 110=6. And this value can be used as integer for calculation purpose.
Can not be understood by humans .
The binary files are read by the Java programs .
We use InputStream and OutPutStream classes when dealing with bytebased data.
Character-Based files(Text Files)
These files are also called text files. Because when the data is taken as input or shown as output,
is in format of sequence of character.
IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code
understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
Byte Stream : It provides a convenient means for handling input and output of byte.
Character Stream : It provides a convenient means for handling input and output of characters.
Character stream uses Unicode and therefore can be internationalized.
Methods
read() : reads byte of data.
write() : Writes byte of data.
Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way.Java application generally uses the data output
stream to write data that can later be read by a data input stream.
Method Description
int size() It is used to return the number of bytes written to the data output stream.
void write(int b) It is used to write the specified byte to the underlying output stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream.
void writeBoolean(boolean v)It is used to write Boolean to the output stream as a 1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeChars(String s) It is used to write string to the output stream as a sequence of
characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte
value.
void writeBytes(String s) It is used to write string to the output stream as a sequence of
bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8
encoding in portable manner.
void flush() It is used to flushes the data output stream.
import java.io.*;
public class OutputExample
{
public static void main(String[] args) throws IOException
{
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
Output:
Succcess...
testout.txt:
A
Java DataInputStream Class
Java DataInputStream class allows an application to read primitive data from the input stream in
a machine-independent way.Java application generally uses the data output stream to write data
that can later be read by a data input stream.
Method Description
int read(byte[] b) It is used to read the number of bytes from the input stream.
int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double value.
boolean readBoolean() It is used to read one input byte and return true if byte is non zero,
false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input stream.
String readUTF() It is used to read a string that has been encoded using the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and store them into the
buffer array.
void readFully(byte[] b, int off, int len) It is used to read len bytes from the input stream.
Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way.Java application generally uses the data output
stream to write data that can later be read by a data input stream.
Method Description
int size() It is used to return the number of bytes written to the data output stream.
void write(int b) It is used to write the specified byte to the underlying output stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream.
void writeBoolean(boolean v)It is used to write Boolean to the output stream as a 1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeChars(String s) It is used to write string to the output stream as a sequence of
characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte
value.
void writeBytes(String s) It is used to write string to the output stream as a sequence of
bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8
encoding in portable manner.
void flush() It is used to flushes the data output stream.
These two abstract classes have several concrete classes that handle unicode character.
Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}
Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException
Program to take String input from Keyboard in Java
import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}
StreamTokenizer
For StreamTokenizer, the source is a character stream, Reader. StreamTokenizer tokenizes the
stream into distinct words and allows to read one by one. It is not a general tokenizer and
includes the capability of knowing the type of the token like the token is a word or number. For
general tokenization, there comes java.util.Scanner where each word or line can read with next(),
nextLine() and nextUTF() methods. StreamTokenizer includes a method nextToken() that can be
used in a for loop to print all the tokens.
The StreamTokenizer comes with the following constant variables (instance variables are also
known as fields) used to decide the type of the token.
int ttype: When the nextToken() returns a token, this field can be used to decide the type of the
token.
static final int TT_EOF: This field is used to know the end of file is reached.
static final int TT_EOL: This field is used to know the end of line is reached.
static final int TT_NUMBER: This field is used to decide the token returned by the
nextToken() method is a number or not.
static final int TT_WORD: This field is used to decide the token returned by the nextToken()
method is a word or not.
String sval: If the token is a word, this filed contains the word that can be used in programming.
double nval: If the token is a word, this filed contains the number that can be used in
programming.
The following program, STDemo.java, reads the AllContent.txt file and prints the number of
numerical values, number of words and number of total characters that appear and the total value
of all the numbers.
import java.io.*;
public class STDemo
{
public static void main(String args[]) throws IOException
{
FileReader freader = new FileReader("AllContent.txt");
StreamTokenizer st = new StreamTokenizer(freader);
double sum = 0;
int numWords = 0, numChars = 0;
while(st.nextToken() != st.TT_EOF)
{
if(st.ttype == StreamTokenizer.TT_NUMBER)
{
sum += st.nval;
}
else if(st.ttype == StreamTokenizer.TT_WORD)
{
numWords++;
numChars += st.sval.length();
}
}
System.out.println("Sum of total numbers in the file: " + sum);
System.out.println("Total words (does not include numbers) in the file: " + numWords);
System.out.println("No. of characters available in words: " + numChars);
}
}
output:
Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive.
Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into
primitive automatically. The automatic conversion of primitive into object is known as
autoboxing and vice-versa unboxing.
The eight classes of java.lang package are known as wrapper classes in java. The list of eight
wrapper classes are given below:
20 20 20
333