0% found this document useful (0 votes)
43 views

SWE1007 - Programming in Java: Prof. A. Vijayarani

The document discusses multithreading concepts in Java including what a thread is, the life cycle of a thread, creating and running threads, and provides examples of multithreading code including one that demonstrates producer and consumer threads communicating using wait and notify methods. It is intended to teach about multithreading programming in Java and covers key topics like thread priorities, thread methods, and how to implement multithreading in a sample program.

Uploaded by

Riajimin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

SWE1007 - Programming in Java: Prof. A. Vijayarani

The document discusses multithreading concepts in Java including what a thread is, the life cycle of a thread, creating and running threads, and provides examples of multithreading code including one that demonstrates producer and consumer threads communicating using wait and notify methods. It is intended to teach about multithreading programming in Java and covers key topics like thread priorities, thread methods, and how to implement multithreading in a sample program.

Uploaded by

Riajimin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 13

SWE1007 Programming

in Java
By

Prof. A. Vijayarani

SITE
VIT

1
Unit IV

Multithreading What is Program, Process, Thread?-


Multiprocessing, Multithreading and Multitasking-Use of
sleep() and suspend methods-Integrated Thread-
Synchronization-Use of wait(), notify() and notifyAll()
methods.

Programming in Java 2
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
Multithreading
Java is a multi-threaded programming language which means we
can develop multi-threaded program using Java. A multi-threaded
program contains two or more parts that can run concurrently and
each part can handle a different task at the same time making
optimal use of the available resources specially when your computer
has multiple CPUs.

By definition, multitasking is when multiple processes share common


processing resources such as a CPU. Multi-threading extends the idea
of multitasking into applications where you can subdivide specific
operations within a single application into individual threads. Each of
the threads can run in parallel.

Multi-threading enables you to write in a way where multiple


activities can proceed concurrently in the same program

Programming in Java 3
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
Life Cycle of a Thread
A thread goes through various stages in its life cycle. For example, a
thread is born, started, runs, and then dies. The following diagram
shows the complete life cycle of a thread.

Programming in Java 4
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
Thread Life Cycle Stages
New: A new thread begins its life cycle in the new state. It remains in
this state until the program starts the thread. It is also referred to as
a born thread.

Runnable: After a newly born thread is started, the thread becomes


runnable. A thread in this state is considered to be executing its task.

Waiting: Sometimes, a thread transitions to the waiting state while


the thread waits for another thread to perform a task. A thread
transitions back to the runnable state only when another thread
signals the waiting thread to continue executing.

Programming in Java 5
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
Thread Life Cycle Stages
Timed Waiting: A runnable thread can enter the timed waiting
state for a specified interval of time. A thread in this state
transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.

Terminated (Dead): A runnable thread enters the terminated


state when it completes its task or otherwise terminates.

Programming in Java 6
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
Thread Priorities
Every Java thread has a priority that helps the operating system
determine the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a
constant of 1) and MAX_PRIORITY (a constant of 10). By default,
every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and
should be allocated processor time before lower-priority threads

Programming in Java 7
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
Thread Methods
Method Description
public void start() Starts the thread in a separate path of
execution, then invokes the run() method
on this Thread object.
public void run() If this Thread object was instantiated using
a separate Runnable target, the run()
method is invoked on that Runnable object.
public final void Changes the name of the Thread object.
setName(String name) There is also a getName() method for
retrieving the name.
public final void Sets the priority of this Thread object. The
setPriority(int priority) possible values are between 1 and 10.

Programming in Java 8
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
Thread Methods
Method Description
public final void The current thread invokes this method on a
join(long millisec) second thread, causing the current thread
to block until the second thread terminates
or the specified number of milliseconds
passes
public final boolean Returns true if the thread is alive, which is
isAlive() any time after the thread has been started
but before it runs to completion.
public final void A parameter of true denotes this Thread as
setDaemon(boolean a daemon thread.
on)
public static void Causes the currently running thread to block
sleep(long millisec) for at least the specified number of
milliseconds. This is static method

Programming in Java 9
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
Create Thread
One of the way to create a thread is to create a new class that extends
Thread class using the following two simple steps. This approach
provides more flexibility in handling multiple threads created using
available methods in Thread class.

Step 1:
You will need to override run( ) method available in Thread class. This
method provides an entry point for the thread and you will put your
complete business logic inside this method. syntax of run() method:
public void run( )

Step 2:
Once Thread object is created, you can start it by calling start( )
method, which executes a call to run( ) method. Syntax of start()
method:
void start( )

Programming in Java 10
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
Multithreading - Sample
Program
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name){
threadName = name; Output:
System.out.println("Creating " + threadName ); }
public void run() { Creating Thread-1
System.out.println("Running " + threadName ); Starting Thread-1
try { Creating Thread-2
for(int i = 4; i > 0; i--) { Starting Thread-2
System.out.println("Thread: " + threadName + ", " + i); Running Thread-1
// Let the thread sleep for a while. Thread: Thread-1, 4
Thread.sleep(50); } } Running Thread-2
catch (InterruptedException e) { Thread: Thread-2, 4
System.out.println("Thread " + threadName + " Thread: Thread-1, 3
interrupted."); } Thread: Thread-2, 3
System.out.println("Thread " + threadName + " exiting."); } Thread: Thread-1, 2
public void start () { Thread: Thread-2, 2
System.out.println("Starting " + threadName ); Thread: Thread-1, 1
if (t == null) { Thread: Thread-2, 1
t = new Thread (this, threadName); Thread Thread-1 exiting.
t.start (); } } } Thread Thread-2 exiting.
public class TestThread {
public static void main(String args[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start(); } }
Programming in Java 11
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
Multithreading Sample
Program
class Q {
class Producer
(Producer
Q q;
andimplements Runnable {
Consumer)
int n; Producer(Q q) {
boolean valueSet = false; this.q = q;
synchronized int get() { new Thread(this, "Producer").start();}
if(!valueSet) public void run() {
try { int i = 0;
wait(); while(true) {
} catch(InterruptedException e) { q.put(i++); }} }
System.out.println("InterruptedException caught");
} class Consumer implements Runnable {
System.out.println("Got: " + n); Q q;
valueSet = false; Consumer(Q q) {
notify(); this.q = q;
return n; } new Thread(this, "Consumer").start(); }
synchronized void put(int n) { public void run() {
if(valueSet) while(true) {
try { q.get(); } } }
wait();
} catch(InterruptedException e) { class PCFixed {
System.out.println("InterruptedException caught"); } public static void main(String args[]) {
this.n = n; Q q = new Q();
valueSet = true; new Producer(q);
System.out.println("Put: " + n); new Consumer(q);
notify(); } System.out.println("Press Control-C to stop."); }
} }

Programming in Java 12
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
Multithreading Sample
Program
Output:
Put: 0
(Producer and Consumer)
Press Control-C to stop.
Got: 0
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
Put: 6
Got: 6
Put: 7
Got: 7
Put: 8
Got: 8
Put: 9
Got: 9
Put: 10
Got: 10
^C

Programming in Java 13
Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

You might also like