Oops Unit-4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

UNIT IV

MULTITHREADING AND GENERIC PROGRAMMING

OBJECTIVES:
• To develop a java application with threads and
generics classes

OUTCOMES:
• Develop Java applications with threads and
generics classes
UNIT IV
MULTITHREADING AND GENERIC PROGRAMMING

Differences between multi-threading and


multitasking, thread life cycle, creating threads,
synchronizing threads, Inter-thread communication,
daemon threads, thread groups.
Generic Programming – Generic classes – generic
methods – Bounded Types – Restrictions and
Limitations
What are threads?
• A thread can be defined as a lightweight process
which can execute multiple codes in parallel

• Threads divide the work of an application into separate


pieces, all of which then run simultaneously.

• The result is a faster and more efficient program, but


along with the increased speed come more difficult
programming and debugging.
What are threads?
• All the java programs have one thread — the main
thread that starts automatically when you run the
program

• In Java, we can create programs that start additional


threads to perform specific tasks

• Video
Examples
• 1. Web browsers can download files while letting you
view web pages. When you download a file in a web
browser, the browser starts a separate thread to handle
the download.
• 2. E-mail programs don’t make you wait for all your
messages to download before you can read the first
message. Instead, these programs use separate threads
to display and download messages.
Examples
• 3. Word processors can print long documents in the
background while you continue to work. These programs
start a separate thread to handle print jobs.

• 4. Word processors can also check your spelling as


you type. Depending on how the word processor is
written, it may run the spell check in a separate thread.
Examples
• 5. Game programs commonly use several threads to
handle different parts of the game to improve the overall
responsiveness of the game.

• 6. All GUI-based programs use at least two threads —


one thread to run the application’s main logic and
another thread to monitor mouse and keyboard events.
Multithreading
Multithreading
Multithreading
• It is a process of executing multiple threads
simultaneously.

• Threads share the same address space.

• A thread is lightweight.

• Cost of communication between the thread is low.


Multitasking
Differences between Multi-threading and Multitasking
S.NO MULTITASKING MULTITHREADING

Many threads are created from a


Users are allowed to perform many
1. process through which computer power
tasks by CPU.
is increased.
It involves often CPU switching CPU switching is often involved
2.
between the tasks. between the threads
The processes share separate
3. Processes are allocated same memory
memory.
Component does not involve
4. Component involves multiprocessing.
multiprocessing.
CPU is provided in order to execute CPU is provided in order to execute
5.
many tasks at a time. many threads from a process at a time.
Processes don’t share same
6. resources, each process is allocated Each process share same resources.
separate resources.
7. It is slow It is faster
Termination of process takes more
8. Termination of thread takes less time.
time.
Thread Life Cycle
Threads can go through five different status in its life
cycle.
1. New
– Soon after the creation of a thread, it is said to be in the new
state.
2. Runnable
– The life of a thread starts after invoking the start () method. The
start() method invokes the run () method.
3. Running
– When the thread is currently running, it is in the state of running.
4. Non-Runnable (Blocked)
– When the thread is still alive, but is currently not eligible to run.
5. Terminated
– When the thread has completed the execution of run () method,
it is said to be in dead state.
Creating Threads

• In java, thread can be created in two ways


1. Extending the Thread class
2. Implementing Runnable interface
Java Thread Methods
Sl.No. Method Description

1) start() It is used to start the execution of the thread.

2) run() It is used to do an action for a thread.


It sleeps a thread for the specified amount of
3) sleep()
time.
4) join() It waits for a thread to die

5) getPriority() It returns the priority of the thread.

6) getName() It returns the name of the thread.

7) setName() It changes the name of the thread.

8) isAlive() It tests if the thread is alive.


The Main Thread
• When a Java program starts up, one thread begins
running immediately, this is usually called the main
thread of the program

• It is the thread from which other “child” threads will be


spawned

• Often, it must be the last thread to finish execution


because it performs various shutdown actions
Controlling the Main Thread

• Although the main thread is created automatically when


your program is started, it can be controlled through a
Thread object

• It is achieved by currentThread( ) method of Thread


Class
// Controlling the Main Thread
class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try
{
for(int n = 5; n > 0; n--)
{
System.out.println(n);
Thread.sleep(1000);
} E:\javapgm>java CurrentThreadDemo
} Current thread: Thread[main,5,main]
catch (InterruptedExceptionAftere) name change: Thread[My Thread,5,main]
{ 5
4
System.out.println("Main thread interrupted");
} 3
} 2
} 1
Creating Threads

• In java, thread can be created in two ways


1. Extending the Thread class
2. Implementing Runnable interface
Extending the Thread class
• The easiest way to create a thread is to write a class that
extends the Thread class
• Syntax:
public class class-name extends Thread
{
public void run()
{
//Code
}
}
class MyThread extends Thread E:\javapgm>java MultiThread
{ Main method: 0
public void run() Main method: 1
Child Thread:0
{
Child Thread:1
for(int count=0;count<=3;count++) Main method: 2
{ Main method: 3
System.out.println("Child Thread:"+count); Child Thread:2
} Child Thread:3
}
}
public class MultiThread
{
public static void main(String[] args)
{
MyThread t1 = new MyThread();
t1.start();
for(int count=0;count<=3;count++)
{
System.out.println("Main method: "+count);
}
}
}
Implementing Runnable Interface
• Runnable interface is available in java.lang package.
• The purpose of Runnable interface is to provide a set of
rules common for objects to execute the functionality
while they are active.
• Syntax:
public class class-name implements Runnable
{
public void run()
{
//Code
}
}
class MyThread implements Runnable E:\javapgm>java MultiThread1
{ Main method: 0
public void run() Main method: 1
Child Thread:0
{
Child Thread:1
for(int count=0;count<=3;count++) Main method: 2
{ Main method: 3
System.out.println("Child Thread:"+count); Child Thread:2
} Child Thread:3
}
}
public class MultiThread1
{
public static void main(String[] args)
{
MyThread dt1 = new MyThread();
Thread t1=new Thread(dt1);
t1.start();
for(int count=0;count<=3;count++)
{
System.out.println("Main method: "+count);
}
}
}
//Thread Life Cycle Methods E:\javapgm>java ThreadMethodsDemo
public class ThreadMethodsDemo extends Thread Thread State-1:NEW
{ Thread State-2:RUNNABLE
public void run()
Thread State-3:RUNNABLE
{
for(int i=0;i<10;i++) Thread State-4:BLOCKED
{ Thread is going to sleep
try Thread Name:Thread-0
{ Thread Priority:5
System.out.println("Thread is going
Thread to sleep");
State5:TIMED_WAITING
ThreadMethodsDemo.sleep(1000);
Thread wake up
System.out.println("Thread wake up");
Thread is going to sleep
}
catch (InterruptedException e) Thread wake up
{ Thread is going to sleep
e.printStackTrace(); Thread wake up
} Thread is going to sleep
} Thread wake up
} Thread is going to sleep
public static void main(String[] args) throws InterruptedException
Thread wake up
{
ThreadMethodsDemo de = new ThreadMethodsDemo(); Thread is going to sleep
Thread wake up
System.out.println("Thread State-1:"+de.getState());
de.start(); Thread is going to sleep
Thread wake up
System.out.println("Thread State-2:"+de.getState());
System.out.println("Thead State-3:"+de.getState());
Thread is going to sleep
System.out.println("Thread State-4:"+de.getState());
Thread wake up
System.out.println("Thread Name:"+de.getName());
Thread is going to sleep
System.out.println("Thread Priority:"+de.getPriority());
Thread wake up
System.out.println("Thread State-5:"+de.getState());
} Thread is going to sleep
} Thread wake up
CREATING MULTIPLE
THREADS
//Creating Multiple threads
class MyThread extends Thread
{
String tname;
MyThread(String name)
{
tname=name;
}
public void run()
{
for(int count=0;count<=3;count++)
{
System.out.println("Child Thread "+tname+":"+count);
}
}
} E:\javapgm>java MultipleThreads
public class MultipleThreads Main method: 0
{ Child Thread One:0
public static void main(String[] args) Child Thread One:1
{ Child Thread Two:0
MyThread t1 = new MyThread("One"); Child Thread Three:0
MyThread t2 = new MyThread("Two"); Child Thread Three:1
MyThread t3 = new MyThread("Three"); Child Thread Three:2
t1.start(); Child Thread Two:1
t2.start(); Child Thread One:2
t3.start(); Main method: 1
for(int count=0;count<=3;count++) Child Thread One:3
{ Child Thread Two:2
System.out.println("Main method: "+count); Child Thread Two:3
} Child Thread Three:3
System.out.println("Done!"); Main method: 2
} Main method: 3
} Done!
Using isAlive( ) and join( )
• isAlive( )
– It returns true if the thread upon which it is called is
still running. It returns false otherwise
• join()
– This method waits until the thread on which it is called
terminates
– Additional forms of join( ) allow you to specify a
maximum amount of time that you want to wait for the
specified thread to terminate.
//join() and isAlive() demo
class NewThread extends Thread
{
String name;
NewThread(String threadname)
{
name = threadname;
System.out.println("New Thread "+name);
}
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Thread "+name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println("Thread "+name + " exiting.");
}
}
class ThreadJoin1
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
ob1.start();
ob2.start();
ob3.start();
System.out.println("Thread One is alive: "+ ob1.isAlive());
System.out.println("Thread Two is alive: "+ ob2.isAlive());
System.out.println("Thread Three is alive: "+ ob3.isAlive());
try
{
System.out.println("Waiting for threads to finish.");
ob1.join();
ob2.join();
ob3.join();
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.isAlive());
System.out.println("Thread Two is alive: "+ ob2.isAlive());
System.out.println("Thread Three is alive: "+ ob3.isAlive());
System.out.println("Main thread exiting.");
}
}
E:\javapgm>java ThreadJoin1
New Thread One
New Thread Two
New Thread Three
Thread One: 5
Thread Three: 5
Thread Two: 5
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
Thread Two: 4
Thread Three: 4
Thread One: 4
Thread One: 3
Thread Three: 3
Thread Two: 3
Thread One: 2
Thread Three: 2
Thread Two: 2
Thread One: 1
Thread Two: 1
Thread Three: 1
Thread One exiting.
Thread Three exiting.
Thread Two exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
Synchronizing Threads
• If you declare any method as synchronized, it is known
as synchronized method.
• Synchronized method is used to lock an object for any
shared resource.
• When a thread invokes a synchronized method, it
automatically acquires the lock for that object and
releases it when the thread completes its task.
• Syntax:
synchronized method-name(arg-list)
{
//method-body
}
class Table class MyThread1 extends Thread
{ {
synchronized void printTable(int n) Table t;
{ MyThread1(Table t)
for(int i=1;i<=5;i++) {
{ this.t=t;
System.out.println(n*i); }
try public void run()
{ {
Thread.sleep(400); t.printTable(5);
} }
catch(Exception e) }
{ class MyThread2 extends Thread
System.out.println(e); {
} Table t;
public class }SyncThread MyThread2(Table t)
{ } {
} public static void main(String args[]) this.t=t;
{ }
Table obj = new Table(); public void run()
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj); {
t1.start(); t.printTable(100);
t2.start(); }
} }
}
Output:

E:\javapgm>java SyncThread
5
10
15
20
25
100
200
300
400
500
Inter-thread Communication
• Inter-thread communication is a mechanism in which a thread
is paused running in its critical section and another thread is
allowed to enter (or lock) in the same critical section to be
executed
• It is implemented by following methods of Object class
– wait()
• tells the calling thread to give up the monitor and go to
sleep until some other thread enters the same monitor
and calls notify( ).
– notify()
• wakes up a thread that called wait( ) on the same
object
– notifyAll()
• wakes up all the threads that called wait( ) on the same
object
• One of the threads will be granted access.
Inter-thread Communication

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the
object. Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified
state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the
monitor state of the object.
class Customer
{
int amount=10000;
synchronized void withdraw(int amt)
{
System.out.println("Withdraw Initiated...");
System.out.println("Account Balance:"+amount);
if(this.amount<amt)
{
System.out.println("Low Balance; Waiting for Deposit...");
try{ wait(); }
catch(Exception e){}
}
this.amount-=amt;
System.out.println("Withdraw Completed...");
System.out.println("Account Balance:"+amount);
}
synchronized void deposit(int amt)
{
System.out.println("Deposit Initiated...");
this.amount+=amt;
System.out.println("Deposit Completed...");
System.out.println("Account Balance:"+amount);
notify();
}
}
class WithdrawThread extends Thread
{
Customer c1;
WithdrawThread(Customer c)
{
c1=c;
}
public void run()
{
c1.withdraw(15000);
}
}
class DepositThread extends Thread
{
Customer c1;
DepositThread(Customer c)
{
c1=c;
}
public void run()
{
c1.deposit(10000);
}
}
class InterThread
{
public static void main(String args[])
{
final Customer c=new Customer();
WithdrawThread w=new WithdrawThread(c);
DepositThread d=new DepositThread(c);
w.start();
d.start();
}
}

Output:
E:\javapgm>java InterThread
Withdraw Initiated...
Account Balance:10000
Low Balance; Waiting for Deposit...
Deposit Initiated...
Deposit Completed...
Account Balance:20000
Withdraw Completed...
Account Balance:5000
Daemon Threads
• A Daemon thread is a background service thread which
runs as a low priority thread and performs background
operations like garbage collection
• setDaemon() method of the Thread class is used to
mark/set a particular thread as a daemon thread
• When we create a thread in java, by default it’s a user
thread
• When a thread is marked as daemon thread, JVM
doesn’t wait it to finish to terminate the program
• As soon as all the user threads are finished, JVM
terminates the program as well as all the associated
daemon threads
public class DaemonThread extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println("This is Daemon Thread");
}
else
{
System.out.println("This is User Thread");
}
}
public static void main(String[] args)
{
DaemonThread t1=new DaemonThread();//creating thread
DaemonThread t2=new DaemonThread();
DaemonThread t3=new DaemonThread();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start(); E:\javapgm>java DaemonThread
t3.start(); This is Daemon Thread
} This is User Thread
} This is User Thread
Thread Groups
• To group multiple threads in a single object

• A thread group can also include the other thread group

• The thread group creates a tree in which every thread


group except the initial thread group has a parent

• Syntax:

new ThreadGroup(String name);

new ThreadGroup(ThreadGroup parent, String name)


public class ThreadGroupDemo implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args)
{
ThreadGroupDemo tgd = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
Thread t1 = new Thread(tg1, tgd,"one");
t1.start();
Thread t2 = new Thread(tg1, tgd,"two");
t2.start();
Thread t3 = new Thread(tg1, tgd,"three");
t3.start();
System.out.println("Thread Group Name: "+tg1.getName());
tg1.list();
}
}
Thread(ThreadGroup group, Runnable target, String name);

• Allocates a new Thread object so that it has target as its run object, has the
specified name as its name, and belongs to the thread group referred to
by group.

E:\javapgm>java ThreadGroupDemo
Thread Group Name: Parent ThreadGroup
three
one
two
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
Suspending and Resuming Thread

• suspend() method allows a thread to


temporarily cease execution.

• The suspended thread can be resumed


using the resume() method.
//suspend() and resume() demo
class NewThread extends Thread
{
String name;
NewThread(String threadname)
{
name = threadname;
System.out.println("New Thread "+name);
}
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Thread "+name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println("Thread "+name + " exiting.");
}
}
class SuspendResume
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
ob1.start();
ob2.start();
try
{
Thread.sleep(1000);
ob1.suspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.resume();
System.out.println("Resuming thread One");
ob2.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.resume();
System.out.println("Resuming thread Two");
}
catch (InterruptedException e) {System.out.println("Main thread Interrupted");}
}
}
OUTPUT:

E:\javapgm>java SuspendResume
New Thread One
New Thread Two
Thread One: 5
Thread Two: 5
Thread Two: 4
Suspending thread One
Thread Two: 3
Resuming thread One
Suspending thread Two
Thread One: 4
Thread One: 3
Thread Two: 2
Resuming thread Two
Thread One: 2
Thread Two: 1
Thread One: 1
Thread Two exiting.
Thread One exiting.
Generic Programming
• Generic classes
• generic methods
• Bounded Types
• Restrictions and Limitations
Generic Classes
Generic Methods
Restrictions and Limitations
Bounded Types

You might also like