Java Unit-3 Threads& Util Packages
Java Unit-3 Threads& Util Packages
UNIT-III
THREADS IN JAVA
Topics covered
Multi Threading
Page 1 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
1. New State:
When we create a thread object using the Thread class, the thread is
born and enters the New state. This means the thread is created, but the
start() method has not yet been called on the instance.
2. Runnable State:
Runnable state means a thread is ready for execution of any statement.
When the start() method is called on a new thread, thread enters into
from New to a Runnable state.
Page 2 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
4. Blocked State:
A thread is considered to be in the blocked state when it is suspended,
sleeping, or waiting for some time in order to satisfy some condition.
A thread can also be dead when the stop() method is called. Once a
thread is in the DEAD state, it cannot be started again.
Thread Methods
Page 3 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
{
MyThread t1 = new MyThread();
t1.start();
}
}
Output
Thread Started Running...
Write a java program to create a thread by implementing runnable
interface
import java.io.*;
import java.util.*;
t1.start();
}
}
Output
Thread is Running Successfully
Page 5 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
try
{
// Sleep for 500 milliseconds
Thread.sleep(5000);
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted");
}
}
}
}
Page 6 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
OUTPUT
Thread 1 - Count : 0
Thread 2 - Count : 0
Thread 1 - Count : 1
Thread 2 - Count : 1
Thread 1 - Count : 2
Thread 2 - Count : 2
Thread 1 - Count : 3
Thread 2 - Count : 3
Thread 2 - Count : 4
Thread 1 - Count : 4
Java provides some handy constants for common priority levels. Let's take a
look:
thread.setPriority(Thread.MAX_PRIORITY);
Page 7 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
In Java, daemon threads are low-priority threads that run in the background
to perform tasks such as garbage collection or provide services to user threads.
This method marks the current thread as a daemon thread or user thread.
Here is an example:
Page 8 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
Page 9 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
Q6)THREAD SYNCHRONIZATION
When we start two or more threads within a program, there may be a situation
when multiple threads try to access the same resource and finally they can
produce unforeseen result due to concurrency issues.
For example, if multiple threads try to write within a same file then they may
corrupt the data because one of the threads can override data or while one
thread is opening the same file at the same time another thread might be
closing the same file.
So there is a need to synchronize the action of multiple threads and make sure
that only one thread can access the resource at a given point in time. This is
implemented using a concept called monitors. Each object in Java is
associated with a monitor, which a thread can lock or unlock. Only one thread
at a time may hold a lock on a monitor.
By the time Passenger1 Thread was successfully able to book ticket and
reduce the available ticket count to 0, and then release object lock by
exiting synchronized block.
Than Passenger2 Thread got a chance to acquire object lock, but available
ticket count at that time was 0 so it wasn’t able to book ticket.
import java.io.*;
class TicketBooking implements Runnable
{
int ticketsAvailable=1;
public void run()
{
Page 10 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
//Let's say system takes some time in booking ticket (here we have taken
1 second time)
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
ticketsAvailable--;
System.out.println("Ticket BOOKED for : "+
Thread.currentThread().getName());
System.out.println("currently ticketsAvailable = "+ticketsAvailable);
}
else
{
System.out.println("Ticket NOT BOOKED for : "+
Thread.currentThread().getName());
}
}//End synchronization block
}
}
public class MyClass
{
public static void main(String args[])
{
TicketBooking obj=new TicketBooking();
Thread thread1=new Thread(obj,"Passenger1 Thread");
Thread thread2=new Thread(obj,"Passenger2 Thread");
thread1.start();
thread2.start();
}
}
Page 11 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
OUTPUT
Waiting to book ticket for : Passenger2 Thread
currently ticketsAvailable = 0
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);
}
Page 12 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
Output:
5
10
15
20
25
100
200
300
400
500
Page 13 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
Page 14 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
PROGRAM:
OUTPUT
GOING TO WITHDRAW
LESS BANCE
WAITING FOR DEPOSIT
GOINGTO DEPOSIT
DEPOSIT COMPLETED
WITHDRAW COMPLETED
Page 15 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
List,
Map,
Set.
The Collection classes:
LinkedList,
HashMap,
TreeSet,
StringTokenizer,
Date,
Random,
Scanner.
List
A list is an ordered collection of elements that can contain duplicates. Lists are
indexed, meaning each element has a specific position. They are useful for
maintaining sequences of items.
Map
Set
A set is an unordered collection of unique elements. Sets are useful for storing
items without duplicates and for performing mathematical set operations like
union, intersection, and difference.
Page 16 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
Array list:
ArrayList is the implementation of List Interface where the elements can be
dynamically added or removed from the list. Also, the size of the list is
increased dynamically if the elements are added more than the initial size.
Syntax:
ArrayList object = new ArrayList ();
Example:
import java.util.*;
class DemoArrayList
{
public static void main(String args[])
{
ArrayList al=new ArrayList(); // creating array list
al.add("kmit"); // adding elements
al.add("Kmec");
al.add("501");
al.add("kmit");
al.set(1,"NGIT");
System.out.println(al.size());
System.out.println(al.indexOf("501"));
al.remove("kmit");
System.out.println(al.lastIndexOf("kmit"));
Iterator itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Linked List: Linked List is a sequence of links which contains items. Each link
contains a connection to another link.
Syntax: Linkedlist object = new Linkedlist();
Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List
Doubly Linked List
import java.util.*;
public class DemoLinked
{
public static void main(String args[])
{
LinkedList<String> list=new LinkedList<String>();
//Adding elements to the Linked list
list.add("Sree");
list.add("Ram");
list.add("Raj");
//Adding an element to the first position
list.addFirst("KMIT");
//Adding an element to the last position
list.addLast("Sita");
//Adding an element to the 3rd position
list.add(2, "NGIT");
list.removeFirst();
Tree Set:
TreeSet is similar to HashSet except that it sorts the elements in the ascending
order while HashSet doesn’t maintain any order. TreeSet allows null element
but like HashSet it doesn’t allow. Like most of the other collection classes this
class is also not synchronized.
Example:
import java.util.TreeSet;
public class TreeSetExample
{
public static void main(String args[])
{
// TreeSet of String Type
TreeSet<String> tset = new TreeSet<String>();
// Adding elements to TreeSet<String>
tset.add("ABC");
tset.add("String");
Page 18 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
tset.add("Test");
tset.add("Pen");
tset.add("Ink");
tset.add("Jack");
//Displaying TreeSet
System.out.println(tset);
// TreeSet of Integer Type
TreeSet<Integer> tset2 = new TreeSet<Integer>();
// Adding elements to TreeSet<Integer>
tset2.add(88);
tset2.add(7);
tset2.add(101);
tset2.add(0);
tset2.add(3);
tset2.add(222);
System.out.println(tset2);
}
}
String Tokenizer:
StringTokenizer class is used for creating tokens in Java. It allows an
application to break or split into small parts. Each split string part is called
Token.
A StringTokennizer in Java, object keeps the string in the present position as it
is to be tokenized. By taking a substring of the string a token can return that
utilize to make the StringTokenizer protest.
Import java.util.*;
Page 19 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
BitSet:
Bitsets represents fixed size sequence of N bits having values either zero or
one. Zero means value is false or unset. One means value is true or set. Bitset
size is fixed at compile time. Bitset is a class defined in java.util package. It is a
special type of array which holds bit values. It implements a vector of bits. Its
size grows automatically as more bits are needed.
This class provides us two types of constructors to form bitset from integers as
well as from strings. Those two are:
Bitset( ): It is a no-argument constructor to create a default object.
Bitset(int size): It is a one-constructor having integer arguments to form an
instance of the bitset class with an initial size of the integer argument
representing the no. of bits.
Example:
import java.util.BitSet;
public class BitSetJavaExample
{
public static void main(String args[])
{
int n=8;
BitSet p = new BitSet(n);
for(int i=0;i<n;i++)
p.set(i);
System.out.print("Bits of p are set as : ");
Page 20 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
for(int i=0;i<n;i++)
System.out.print(p.get(i)+" ");
BitSet q = (BitSet) p.clone();
System.out.print("nBits of q are set as : ");
for(int i=0;i<n;i++)
System.out.print(q.get(i)+" ");
for(int i=0;i<3;i++)
p.clear(i);
System.out.print("nBits of p are now set as : ");
for(int i=0;i<n;i++)
System.out.print(p.get(i)+" ");
System.out.print("nBits of p which are true : "+p);
System.out.print("The Bits of q which are true : "+q);
BitSet r= (BitSet) p.clone();
p.xor(q);
System.out.println("Output of p xor q= "+p);
p = (BitSet) r.clone();
p.and(q);
System.out.println("Output of p and q = "+p);
p = (BitSet) r.clone();
p.or(q);
System.out.println("Output of p or q = "+p);
}
}
Date class
Specify the desired pattern while creating the instance of SimpleDateFormat.
Create an object of Date class. Call the format() method of DateFormat class
and pass the date object as a parameter to the method.
Page 21 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
{
//"hh" in pattern is for 12 hour time format and "aa" is for AM/PM
SimpleDateFormat dateTimeInGMT = new SimpleDateFormat("yyyy-MMM-dd
hh:mm:ss aa");
//Setting the time zone
dateTimeInGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateTimeInGMT.format(new Date()));
}
}
Calendar class
Specify the desired pattern for the date and time. Similar to the step 1 of above
method. Create an object of Calendar class by calling getInstance() method of
it. Call the format() method of DateFormat and pass the Calendar.getTime() as
a parameter to the method.
Page 22 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
Formatter
Java Formatter is a utility class that can make life simple when working with
formatting stream output in Java. It is built to operate similarly to the C/C++
printf function. It is used to format and output data to a specific destination,
such as a string or a file output stream
Formatter Construction
Page 23 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java
Page 24 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad