0% found this document useful (0 votes)
32 views10 pages

Unit 4 Final

This document provides an overview of multithreading concepts in Java, including: 1) Thread life cycle stages like new, runnable, waiting, timed waiting, and terminated. 2) Two ways to create threads - extending the Thread class or implementing Runnable interface. 3) Common thread methods like start(), run(), join(), getName(), setName(), etc. 4) Synchronization techniques like synchronized methods and blocks to control access to shared resources and prevent interference between threads.

Uploaded by

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

Unit 4 Final

This document provides an overview of multithreading concepts in Java, including: 1) Thread life cycle stages like new, runnable, waiting, timed waiting, and terminated. 2) Two ways to create threads - extending the Thread class or implementing Runnable interface. 3) Common thread methods like start(), run(), join(), getName(), setName(), etc. 4) Synchronization techniques like synchronized methods and blocks to control access to shared resources and prevent interference between threads.

Uploaded by

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

US05CBCA25 OOP-III UNIT - 4

Shri D.N.Institute of Computer Applications


Managed By Charotar Education Society
BCA Sem – 5
US05CBCA25 – OOP- III

Topics : Multithreading
Introduction
Thread Life Cycle
Creating Thread
Thread Methods
Thread Synchronization

Introduction

• Multithreading in Java allows concurrent execution of two or more parts of a


program for maximum utilization of CPU. Each part of such program is called a
thread.
• Each of the threads can run in parallel. The OS divides processing time not only
among different applications, but also among each thread within an application.
• Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
• Every java program creates at least one thread [ main() thread ]. Additional
threads are created through the Thread constructor or by instantiating classes that
extend the Thread class.

Thread Characteristics:

• Facility to allow multiple activities within a single process


• Referred as lightweight process
• A thread is a series of executed statements
• Each thread has its own program counter, stack and local variables
• A thread is a nested sequence of method calls
• Its shares memory, files and per-process state
Why we use Threads?
• To perform asynchronous or background processing
• Increases the responsiveness of GUI applications
• Take advantage of multiprocessor systems
• Simplify program logic when there are multiple independent entities

Compiled By : Tulsi Shah Page 4


US05CBCA25 OOP-III UNIT - 4

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.

Following are the stages of the life cycle −

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.

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. This state can be
achieved by sleep() method.

Terminated (Dead) − A runnable thread enters the terminated state when it completes
its task or otherwise terminates.

Thread creation in Java (implementation)


Thread implementation in java can be achieved in two ways:
1. Extending the java.lang.Thread class
2. Implementing the java.lang.Runnable Interface

By extending thread class


• The class should extend Java java.lang.Thread class.
• The class should override the run() method.

Compiled By : Tulsi Shah Page 5


US05CBCA25 OOP-III UNIT - 4

• The functionality that is expected by the Thread to be executed is written in the run()
method.
• void start(): Creates a new thread and makes it runnable.
• void run(): The new thread begins its life inside this
method. Example:
public class MyThread extends
Thread { public void run(){
System.out.println("thread is
running...");
}
public static void main(String[]
args) { MyThread obj = new
MyThread(); obj.start();
}
By Implementing Runnable interface
• The class should implement the Runnable interface
• The class should implement the run() method in the Runnable interface
• The functionality that is expected by the Thread to be executed is put in the
run() method Example:
public class MyThread implements Runnable
{ public void run()
{
System.out.println("thread is running..");
}
public static void main(String[] args)
{
Thread t = new Thread(new MyThread());
t.start();
}

Thread Methods

Method Description
String getName() Retrieves the name of running thread in the current context in
String format
void setName(String s) Setting thread name
Thread.State It returns the state of the thread.
getState()
void start() This method will start a new thread of execution by calling run()
method of Thread/runnable object.
void run() This method is the entry point of the thread. Execution of thread
starts from this method.
void join() This method used to queue up a thread in execution. Once
called on thread, current thread will wait till calling thread

Compiled By : Tulsi Shah Page 6


US05CBCA25 OOP-III UNIT - 4

completes its execution

boolean isAlive() This method will check if thread is alive or dead.

Thread interruption methods (Java Concurrency )

void sleep(int time) This method suspend the thread for mentioned time duration in
argument (sleeptime in milliseconds)
void yield() By invoking this method the current thread pause its execution
temporarily and allow other threads to execute.
void wait() when wait() method is invoked on an object, the thread
executing that code gives up its lock on the object immediately
and moves the thread to the wait state.
void notify() This wakes up threads that called wait() on the same object and
moves the thread to ready state.
void notifyAll() This wakes up all the threads that called wait() on the same
object.
void interrupt() Interrupts this thread.
boolean interrupted() Tests whether the current thread has been interrupted.

Thread priority methods

void setPriority(int p) modify a thread’s priority at any time after its


creation. MIN_PRIORITY (1), NORM_PRIORITY and
MAX_PRIORITY (10) . The
higher the integer, the higher the priority.Normally the thread
priority will be 5.
int getPriority() Return value of priority of current thread.

Thread Scheduling
• Execution of multiple threads on a single CPU, in some order, is called scheduling.
• In general, the runnable thread with the highest priority is active (running)
• Java is priority-preemptive. If a high-priority thread wakes up, and a low-priority
thread is running then the high-priority thread gets to run immediately Allows on-
demand processing.
• Efficient use of CPU

Thread Synchronization
• Synchronization in java is the capability to control the access of multiple threads to
any shared resource.
• Java Synchronization is better option where we want to allow only one thread to
Compiled By : Tulsi Shah Page 7
US05CBCA25 OOP-III UNIT - 4

access the shared resource.

Why use Synchronization

The synchronization is mainly used to


• To prevent thread interference.
• To prevent consistency problem.

Types of Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive : Mutual Exclusive helps keep threads from interfering with
one another while sharing data. This can be done by three ways in java:
1.1). Synchronized method.
1.2). Synchronized block.
1.3). static synchronization.
2. Cooperation (Inter-thread communication in java) : Cooperation (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.

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent
access to an object's fields has to acquire the object's lock before accessing them, and
then release the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock


implementations.

Implementing synchronization example

Without Synchronization Synchronized method


class Table{ class Table{
void printTable(int n){ synchronized void printTable(int n){
//method not synchronized //synchronized method
for(int i=1;i<=5;i++){ for(int i=1;i<=5;i++){
System.out.println(n*i); System.out.println(n*i);
try{ try{
Thread.sleep(400); Thread.sleep(400);
}catch(Exception }catch(Exception
e){System.out.println(e);} e){System.out.println(e);}
} }
} }

Compiled By : Tulsi Shah Page 8


US05CBCA25 OOP-III UNIT - 4

} }

class MyThread1 extends Thread{ class MyThread1 extends Thread{


Table t; Table t;
MyThread1(Table t){ MyThread1(Table t){
this.t=t; this.t=t;
} }
public void run(){ public void run(){
t.printTable(5); t.printTable(5);
} }
} }
class MyThread2 extends Thread{ class MyThread2 extends Thread{
Table t; Table t;
MyThread2(Table t){ MyThread2(Table t){
this.t=t; this.t=t;
} }
public void run(){ public void run(){
t.printTable(100); t.printTable(100);
} }
} }

class TestSynchronization1{ public class TestSynchronization2{


public static void main(String args[]){ public static void main(String args[]){
Table obj = new Table(); //only one object Table obj = new Table(); //only one object
MyThread1 t1=new MyThread1(obj); MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj); MyThread2 t2=new MyThread2(obj);
t1.start(); t1.start();
t2.start(); t2.start();
} }
} }
Output: Output:
5 5
100 10
10 15
200 20
15 25
300 100
20 200
400 300
25 400
500 500

Disclaimer: The study material is compiled by Ms. Tulsi Shah. The basic objective of this
material is to supplement teaching and discussion in the classroom in the subject. Students are
required to go for extra reading in the subject through Library books recommended by Sardar
Patel University, Vallabh Vidyanagar. Students should also consult the subject teacher for the
solution of their problems in order to enhance their subject knowledge.

Compiled By : Tulsi Shah Page 9


US05CBCA25 OOP-III UNIT - 4

Compiled by : Tulsi Shah Page 10


US05CBCA25 OOP-III UNIT - 4

Question Bank
MCQs
1. Which are the methods of the object class?
A. notify(); C. wait(long msces);
B. notifyAll(); D. All of them
2. Which will contain the body of the thread?
A. run(); C. start();
B. wait(); D. terminate();
3. Which is the name of the method used to start a thread execution?
A. wait(); C. terminate();
B. start(); D. notify();
4. Which class or interface defines the wait(), notify() and notifyAll() methods?
A. Runnable C. Object
B. Thread D. None of Above
5. What are the two valid constructor for Thread?
A. Thread() , Thread(int priority) C. Thread(), Thread(Runnable r, String
name)
B. Thread() ,Thread(Runnable r, D. Thread(), Thread(int pripority)
ThreadGroup g)
6. Which is not the method defined in class Thread?
A. wait(): C. start();
B. run(); D. stop();
7. Which method of the thread class is used to find out the priority given to a thread?
A. get(); C. getPriority();
B. threadPriority(); D. getThreadPriority();
8. What is the output in the following thread java program?
Class thread_example
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println(t.isAlive());
}
}

A. 0 C. false
B. 1 D. true
9. Which function of pre defined class Thread is used to check if current thread being
checked is still running?
A. join(); C. alive();
B. isRunning(); D. isAlive();
10. When a class extends the thread class, it should override ____________ method of thread
class to start the thread.
A. start(); C. run();
B. go(); D. init();
11. In java a thread can be created by ___________
A. Extended the thread class C. Implementing Runnable
interface.

Compiled by : Tulsi Shah Page 11


US05CBCA25 OOP-III UNIT - 4

B. Both of above() D. None of these


12.

Which method is called internally by Thread start() method?


A. run(); C. execute();
B. main(); D. launch();
13. Thread synchronization in a process will be required when ___________________
A. All thread sharing same address C. All thread sharing same files
space
B. All thread sharing same global D. All of above
variable
14. Which method is used to get current running thread object?
A. runningThread(); C. currentThread();
B. runnableThread(); D. None of Above
15. The life cycle of thread in java is controlled by ____________
A. JVM C. JRE
B. JDK D. None of Above
16. Min and Max priority of thread in java multithreading are_____________
A. 1, 10 C. 0, 255
B. 0, 10 D. 1, 256
17. Which method we implement from runnable interface?
A. start(); C. execute();
B. run(); D. call();
18. What is sometimes called a lightweight process?
A. Process C. JVM
B. Thread D All of above
19. Which method restart the thread?
A. start(); C. restartThread();
B. restart(); D. None of above.
20. Which method we implement from runnable interface?
A. StringBuilder C. StringBuffer
B. All of above D. None of Above

Compiled by : Tulsi Shah Page 12


US05CBCA25 OOP-III UNIT - 4

Short Question
1) What is Java Thread?
2) Write down Thread characteristics.
3) List Thread implementation in java. Explain any one.
[ or explain Java Thread implementation By extending thread class / By Implementing
Runnable interface]
4) List Java Thread Methods.
5) Define the following.[Any]
a. String getName()
b. void setName(String s)
c. Thread.State getState()
d. void start()
e. void run()
f. void join()
g. boolean isAlive()
h. void sleep(int time)
i. void yield()
j. void wait()
k. void notify()
l. void notifyAll
m. void interrupt()
n. boolean interrupted()
o. void setPriority(int p)
p. int getPriority()
6) What is Thread Scheduling?

Long Question
1) 1. What is Threads? Which are the Characteristics of Thread and why we use Thread?
2) 2. Draw Life Cycle of a Thread and explain in detail.
3) 3. Explain Thread creation in Java.
4) 4. List Thread methods and explain any five.
5) 5. Explain Thread Synchronization and how to Implement synchronization with example.

Compiled by : Tulsi Shah Page 13

You might also like