Unit 4
Unit 4
1. Threading
1.1. Introduction
• Java provides built-in support for multithreaded programming. A multithreaded program
contains two or more parts that can run concurrently.
• Each part of such a program is called a thread, and each thread defines a separate path
of execution. Thus, multithreading is a specialized form of multitasking.
• Two distinct types of multitasking:
o process-based:
▪ process-based multitasking is the feature that allows your computer to
run two or more programs concurrently. For example, process-based
multitasking enables you to run the Java compiler at the same time that
you are using a text editor. In process-based multitasking, a program is
the smallest unit of code that can be dispatched by the scheduler.
▪ process-based multitasking deals with the “big picture,”
▪ Processes are heavyweight tasks that require their own separate address
spaces. Interprocess communication is expensive and limited. Context
switching from one process to another is also costly.
▪ process-based multitasking is not under the control of Java.
o thread-based:
▪ thread-based multitasking environment, the thread is the smallest unit
of dispatchable code. This means that a single program can perform two
or more tasks simultaneously. For instance, a text editor can format text
at the same time that it is printing, as long as these two actions are being
performed by two separate threads.
▪ thread-based multitasking handles the details.
▪ Threads, on the other hand, are lightweight. They share the same
address space and cooperatively share the same heavyweight process.
Interthread communication is inexpensive, and context switching from
one thread to the next is low cost.
▪ Multithread multitasking is under the control of Java.
• Life cycle of a thread (thread states)
1
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
o In Java, a thread always exists in any one of the following states. These states
are:
o New
▪ Whenever a new thread is created, it is always in the new state. For a
thread in the new state, the code has not been run yet and thus has not
begun its execution.
o Active
▪ When a thread invokes the start() method, it moves from the new state
to the active state. The active state contains two states within it: one is
runnable, and the other is running.
▪ Runnable: A thread, that is ready to run is then moved to the runnable
state. In the runnable state, the thread may be running or may be ready
to run at any given instant of time. It is the duty of the thread scheduler
to provide the thread time to run, i.e., moving the thread the running
state.
▪ Running: When the thread gets the CPU, it moves from the runnable to
the running state. Generally, the most common change in the state of a
thread is from runnable to running and again back to runnable.
o Blocked / Waiting
▪ Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.
o Timed Waiting
▪ Sometimes, waiting for leads to starvation. For example, a thread (its
name is A) has entered the critical section of a code and is not willing to
leave that critical section. In such a scenario, another thread (its name is
B) has to wait forever, which leads to starvation. To avoid such scenario,
a timed waiting state is given to thread B. Thus, thread lies in the waiting
state for a specific span of time, and not forever. A real example of timed
waiting is when we invoke the sleep() method on a specific thread. The
sleep() method puts the thread in the timed wait state. After the time
runs out, the thread wakes up and start its execution from when it has
left earlier.
o Terminated
▪ A thread reaches the termination state because of the following reasons:
• When a thread has finished its job, then it exists or terminates
normally.
• Abnormal termination: It occurs when some unusual events
such as an unhandled exception or segmentation fault.
1.2. Ways to define
• There are two ways to create a thread:
o By extending Thread class
o By implementing Runnable interface
2
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
• Thread class:
o Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and implements
Runnable interface.
o Commonly used Constructors of Thread class:
▪ Thread()
▪ Thread(String name)
▪ Thread(Runnable r)
▪ Thread(Runnable r, String name)
o Commonly used methods of Thread class:
▪ public void run(): is used to perform action for a thread.
▪ public void start(): starts the execution of the thread. JVM calls the run()
method on the thread.
▪ public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified number
of milliseconds.
▪ public void join(): waits for a thread to die.
▪ public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
▪ public int getPriority(): returns the priority of the thread.
▪ public int setPriority(int priority): changes the priority of the thread.
▪ Etc.
• Runnable interface:
o The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().
o public void run(): is used to perform action for a thread.
Output:
thread is running...
}
}
Output: My first thread
// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
Output:
My new thread
Now the thread is running ...
5
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
Thread.currentThread().setPriority(10);
6
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Output:
Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
1.6. Yield()
▪ The yield() method of thread class causes the currently executing thread object to
temporarily pause and allow other threads to execute.
▪ Ex.
public class JavaYieldExp extends Thread
{
public void run()
{
for (int i=0; i<3 ; i++)
System.out.println(Thread.currentThread().getName() + " in control");
}
public static void main(String[]args)
{
JavaYieldExp t1 = new JavaYieldExp();
JavaYieldExp t2 = new JavaYieldExp();
// this will call run() method
t1.start();
t2.start();
for (int i=0; i<3; i++)
{
// Control passes to child thread
t1.yield();
System.out.println(Thread.currentThread().getName() + " in control");
}
}
}
Output:
main in control
main in control
7
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
main in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-1 in control
Thread-1 in control
Thread-1 in control
1.7. Sleep()
• The method sleep() is being used to halt the working of a thread for a given amount of time.
• The Java Thread class provides the two variant of the sleep() method. First one accepts only
an arguments, whereas the other variant accepts two arguments.
• The time up to which the thread remains in the sleeping state is known as the sleeping time
of the thread.
• After the sleeping time is over, the thread starts its execution from where it has left.
• The sleep() Method Syntax:
o public static void sleep(long mls) throws InterruptedException
o public static void sleep(long mls, int n) throws InterruptedException
o Parameters:
▪ mls: The time in milliseconds is represented by the parameter mls. The
duration for which the thread will sleep is given by the method sleep().
▪ n: It shows the additional time up to which the programmer or developer
wants the thread to be in the sleeping state. The range of n is from 0 to
999999.
• Example of the sleep() method in Java : on the custom thread
Ex.
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
// the thread will sleep for the 500 milli seconds
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
t1.start();
t2.start();
}
}
Output: 1 1 2 2 3 3 4 4
8
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
// The main thread sleeps for the 1000 milliseconds, which is 1 sec
// whenever the loop runs
Thread.sleep(1000);
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.print(“ “+i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Output:
123451122334455
We can see in the above example, when t1 completes its task then t2 and t3 starts executing.
1.9. Synchronization
• The process of allowing multiple threads to modify an object in a sequence is called
synchronization. This is possible by using an object locking concept.
• Thread Synchronization is a process of allowing only one thread to use the object when
multiple threads are trying to use the particular object at the same time. To achieve this
Thread Synchronization we have to use a java keyword or modifier called
“synchronized”.
• General Syntax:
synchronized(objectidentifier)
{
// Access shared variables and other shared resources;
}
Output:
1 booked to t1
2 booked to t2
3 booked to t3
11
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
}
}
Outuput:
1 booked to t1
No tickets to book
2 booked to t2
Ex.
class Buffer{
int a;
boolean produced = false;
13
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
}catch(Exception e){
System.out.println(e);
}
}
System.out.println("Product" + a + " is consumed.");
produced = false;
notify();
}
}
14
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
//starting threads.
p.start();
c.start();
}
}
Output:
Consumer start consuming...
Consumer is waiting...
Producer start producing...
Product1 is produced.
Producer is waiting...
Product1 is consumed.
Consumer is waiting...
Product2 is produced.
Producer is waiting...
Product2 is consumed.
Consumer is waiting...
Product3 is produced.
Producer is waiting...
Product3 is consumed.
Consumer is waiting...
Product4 is produced.
Producer is waiting...
Product4 is consumed.
Consumer is waiting...
Product5 is produced.
Product5 is consumed.
15
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
oWhen we create a new thread for executing a new task cause overhead of thread
creation. In order to manage this thread life-cycle, the execution time increase
respectively.
• Types of Executors
In Java, there are different types of executors available which are as follows:
2. Generics
2.1. Generic Methods
• It would be nice if we could write a single sort method that could sort the elements in an
Integer array, a String array, or an array of any type that supports ordering.
• Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of
related types, respectively.
• You can write a single generic method declaration that can be called with arguments of
different types.
• Ex.
public class GenericMethodTest {
16
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
17
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Ex.
class A
{
public void displayClass()
{
System.out.println("Inside super class A");
}
}
class B extends A
{
public void displayClass()
{
System.out.println("Inside sub class B");
}
}
class C extends A
{
public void displayClass()
{
System.out.println("Inside sub class C");
}
}
18
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
bec.doRunTest();
beb.doRunTest();
bea.doRunTest();
//bea.doRunTest();
• Multiple bounds
o Ex.
class Bound<T extends A & B>
{
private T objRef;
19
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
interface B
{
public void displayClass();
}
class A implements B
{
public void displayClass()
{
System.out.println("Inside super class A");
}
}
}
}
}
}
}
}
Output:
ArrayList Collection
LinkedList Collection
HashSet Collection
Comparable Comparator
2) Comparable affects the original class, Comparator doesn't affect the original
i.e., the actual class is modified. class, i.e., the actual class is not modified.
21
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
5) We can sort the list elements of We can sort the list elements of Comparator
Comparable type type by Collections.sort(List,
by Collections.sort(List) method. Comparator) method.
Output: Erro-> The method sort(List<T>) in the type Collections is not applicable
for the arguments (ArrayList<Student>)
Ex.
import java.util.*;
@Override
//Override compareTo method to customizing sorting algorithm
public int compareTo(Student stu) {
return (this.id - stu.id);
}
@Override
//Override toString method to return Student details
public String toString() {
return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age +"]";
}
System.out.println(student);
}
}
}
• Comparator interface: Like Comparable interface, Comparator interface also used to sort
a collection of custom objects and it is defined in java.util package. Its compare(Object
obj1,Object obj2) method have to be implemented. The compare(Object obj1,Object
obj2) method have to implemented in such a way that it will return a negative int value,
zero, or a positive int value if first object/argument is less than, equal to, or greater than
the second object/argument.
Ex.
import java.util.*;
import java.io.*;
class Student {
private int id;
private String name;
private int age;
//Compare based on id
public static Comparator<Student> IdComparator = new Comparator<Student>() {
@Override
public int compare(Student stu1, Student stu2) {
25
Subject: Programming with Java (102044502)
Unit 4: Threading, Generics
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
@Override
public int compare(Student stu1, Student stu2) {
return stu1.getName().compareTo(stu2.getName());
}
};
@Override
//Override toString method to return Student details
public String toString() {
return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age +"]";
}
27