Unit - IV Notes (2)
Unit - IV Notes (2)
Unit - IV Notes (2)
UNIT IV
All the tasks are executed without affecting the main program. In a program or
process, all the threads have their own separate path for execution, so each
thread of a process is independent.
Thread Model
2) Running
A thread is in a Running state when it is under execution.
3) Suspended
4) Blocked
5) Terminated
A thread comes in this state when at any given time, it halts its execution
immediately.
Creating Thread
Thread Class
o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name, long
stackSize)
start() method
The method is used for starting a thread that we have newly created. It starts a
new thread with a new callstack. After executing the start() method, the thread
changes the state from New to Runnable. It executes the run() method when
the thread gets the correct time to execute it.
Example Program:
Output:
In Java, we can also create a thread by implementing the runnable interface. The
runnable interface provides us both the run() method and the start() method.
Example Program
Output
Thread class provide constructors and methods to create and perform operations
on a thread.Thread class extends Object class and implements Runnable
interface.
Runnable interface:
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It
performs the following tasks
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It
performs the following tasks
Output:
thread is running...
Output:
thread is running...
We can directly use the Thread class to spawn new threads using the
constructors defined above.
Output:
My first thread
Creating a Thread by implementing Runnable Interface
The runnable interface has an undefined method run() with void as return type,
and it takes in no arguments. The method summary of the run() method is given
below-
The runnable interface provides a standard set of rules for the instances of
classes which wish to execute code when they are active. The most common use
case of the Runnable interface is when we want only to override the run
method. When a thread is started by the object of any class which is
implementing Runnable, then it invokes the run method in the separately
executing thread.
Implementing Runnable
The thread will execute the code which is mentioned in the run() method of the
Runnable object passed in its argument.
Example
@Override
public void run() {
System.out.println("Thread has ended");
}
Output
Thread vs. Runnable
Syntax
Parameter
Return
1) wait() method
The 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.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws It waits for the specified amount of time.
InterruptedException
2) notify() method
The 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. The choice is arbitrary and occurs at the discretion of the
implementation.
Syntax:
3) notifyAll() method
Let's see the important differences between wait and sleep methods.
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
All the legacy classes are synchronized. The java.util package defines the
following legacy classes:
1. HashTable
2. Stack
3. Dictionary
4. Properties
5. Vector
Vector Class
1) Vector()
It is used when we want to create a default vector having the initial size of 10.
2) Vector(int size)
4) Vector(Collection c)
It is used to create a vector with the same elements which are present in the
collection. It accepts the collection as a parameter.
import java.util.*;
public class VectorExample
{
public static void main(String[] args)
{
Vector<String> vec = new Vector<String>();
vec.add("Emma");
vec.add("Adele");
vec.add("Aria");
vec.add("Aidan");
vec.add("Adriana");
vec.add("Ally");
Enumeration<String> data = vec.elements();
while(data.hasMoreElements())
{
System.out.println(data.nextElement());
}
}
}
Output:
Example Program
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
Output
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
In Java, Stack is a class that falls under the Collection framework that extends
the Vector class. It also implements interfaces List, Collection, Iterable,
Cloneable, Serializable. It represents the LIFO stack of objects. Before using
the Stack class, we must import the java.util package.
The Stack class contains only the default constructor that creates an empty
stack.
public Stack()
Creating a Stack
If we want to create a stack, first, import the java.util package and create an
object of the Stack class.
Or
Where type denotes the type of stack like Integer, String, etc.
We can perform push, pop, peek and search operation on the stack. The Java
Stack class provides mainly five methods to perform these operations. Along
with this, it also provides all the methods of the Java Vector class.
push(E item) E The method pushes (insert) an element onto the top
of the stack.
search(Object int The method searches the specified object and returns
o) the position of the object.
The empty() method of the Stack class check the stack is empty or not. If the
stack is empty, it returns true, else returns false. We can also use the isEmpty()
method of the Vector class.
Syntax
The method inserts an item onto the top of the stack. It works the same as the
method addElement(item) method of the Vector class. It passes a
parameter item to be pushed into the stack.
Syntax
Returns: The method returns the argument that we have passed as a parameter.
The method removes an object at the top of the stack and returns the same
object. It throws EmptyStackException if the stack is empty.
Syntax
public E pop()
Syntax
public E peek()
The method searches the object in the stack from the top. It parses a parameter
that we want to search for. It returns the 1-based location of the object in the
stack. Thes topmost object of the stack is considered at distance 1.
Suppose, o is an object in the stack that we want to search for. The method
returns the distance from the top of the stack of the occurrence nearest the top of
the stack. It uses equals() method to search an object in the stack.
Syntax
Returns: It returns the object location from the top of the stack. If it returns -1,
it means that the object is not on the stack.
Java Collections enumeration() Method
Syntax
Parameter
Returns
import java.util.*;
public class CollectionsEnumerationExample1 {
public static void main(String[] args) {
Vector<String> Enum = new Vector<String>();
Enum.add("JAVA");
Enum.add("JSP");
Enum.add("SERVLET");
Enum.add("C");
Enum.add("PHP");
Enum.add("PERL");
//Create Enumeration
Enumeration<String> en = Collections.enumeration(Enum);
System.out.println("The Enumeration List are: ");
while(en.hasMoreElements()){
System.out.println(en.nextElement());
}
}
}
Output:
Java.util Package
It contains the collections framework, legacy collection classes, event model, date
and time facilities, internationalization, and miscellaneous utility classes (a string
tokenizer, a random-number generator, and a bit array).
StringTokenizer in Java
Constructor Description
Methods Description
Output:
my
name
is
khan
Java Calendar Class
Java Calendar class is an abstract class that provides methods for converting
date between a specific instant in time and a set of calendar fields such as
MONTH, YEAR, HOUR, etc. It inherits Object class and implements the
Comparable interface.
No Method Description
2. public boolean after The method Returns true if the time represented
(Object when)
by this Calendar is after the time represented
by when Object.
when Object.
4. public final void Set the given calendar field value and the time
clear(int field)
value of this Calendar undefined.
Output:
The initialization of the cal object is done with the current date and time in the
default locale and timezone.
We can instantiate the GregorianCalendar class because of being a concrete
class.
The initialization of the gcal object is done with the current date and time in the
default locale and timezone.
The anno Domini(AD) and the Before Christ(BC) are the two fields defined
by the GregorianCalendar class.
Java Scanner
Scanner class in Java is found in the java.util package. Java provides various
ways to read input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default. It provides many methods to read and parse various
primitive values.
The Java Scanner class is widely used to parse text for strings and primitive
types using a regular expression. It is the simplest way to get input in Java. By
the help of Scanner in Java, we can get input from the user in primitive types
such as int, long, double, byte, float, short, etc.
The Java Scanner class extends Object class and implements Iterator and
Closeable interfaces.
To get the instance of Java Scanner which reads input from the user, we need to
pass the input stream (System.in) in the constructor of Scanner class. For
Example:
To get the instance of Java Scanner which parses the strings, we need to pass
the strings in the constructor of Scanner class. For Example:
SN Constructor Description
of a pattern constructed
from the specified
string,
ignoring delimiters.
ignoring delimiters.
method or not.
method or not.
or not.
or not.
Example
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Output:
The Collections utility class consists exclusively of static methods that operate
on or return collections. It contains polymorphic algorithms that operate on
collections, "wrappers", which return a new collection backed by a specified
collection,
import java.util.Collections;
import java.util.*;
myFirstList.add(20);
myFirstList.add(20);
myFirstList.add(50);
myFirstList.add(70);
mySecondList.add(11);
mySecondList.add(120);
mySecondList.add(120);
mySecondList.add(150);
mySecondList.add(170);
Collections.copy(mySecondList, myFirstList );