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

Module Vi Oops 1

Uploaded by

suhaebn.shaik
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)
5 views

Module Vi Oops 1

Uploaded by

suhaebn.shaik
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/ 29

Module-6-Concurrent Programming

Multi-Threaded Programming – Process Vs Thread - Thread Life Cycle -


Thread class – Runnable interface- Thread Creation- Interrupting Threads
– Thread States – Thread Properties –-Thread Control and Priorities -
Inter Thread Communication -Thread Synchronization –
Synchronization.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Multi-Threaded Programming
• Multithreading in Java is a process of executing multiple threads simultaneously.
• The primary purpose of multithreading is to provide simultaneous execution of two or
more parts of a program to make maximum use of CPU time.
• 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.
• Multithreading is generally used in games, animation etc.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Thread Life Cycle

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java Thread class
• Java’s multithreading system is built upon the Thread class, its methods, and its
companion interface, Runnable.
• Thread class provides constructors and methods to create and perform operations on
a thread.

Methods in Thread class:


start(): Start a thread by calling its run method
run(): Entry point for the thread
getName(): Obtain a thread’s name.
setName(): changes the name of the thread
getPriority(): Obtain a thread’s priority.
setPriority(int pri): changes the priority of the thread
sleep(long ms): Suspend a thread for a period of time.
currentThread(): returns the currently executing thread

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


The Main Thread
• When a Java program starts up, one thread begins running immediately. This is
usually called the main thread of your program, because it is the one that is executed
when your program begins.
The main thread is important for two reasons:
• 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

class main{
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
}
Current thread: Thread[#1,main,5,main]
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Creating a Thread
Java defines two ways in which this can be accomplished:

1.Extending the Thread class.


2.Implementing the Runnable interface.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Creating a Thread using Thread class

• The first way to create a thread is to create a new class that extends Thread class
• The extending class must override the run( ) method, which is the entry point for the
new thread.
• Create an instance of that class.
• It must also call start( ) to begin execution of the new thread.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Creating a Thread using Thread class
class MultiThreadDemo {
public static void main(String args[]) {
NewThread t1=new NewThread();
class NewThread extends Thread { NewThread t2=new NewThread();
NewThread t3=new NewThread();
// This is the entry point for thread. t1.start();
public void run() { t2.start();
for(int i = 0; i <3; i++) { t3.start();
Thread-1: 0
System.out.println(Thread.currentThread()+ ": " + i); }
Thread-1: 1
} } Thread-1: 2
} Thread-0: 0
} Thread-0: 1
Thread-0: 2
Thread-2: 0
Thread-2: 1
Thread-2: 2

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Creating a Thread using Thread class
Write a program to create two child threads first thread display factorial given number and
second thread displays sum of n numbers.

class Fact extends Thread { class Sum extends Thread { class Factsum{
int n; int n; public static void main(String
Fact(int n) Sum(int n) args[]) {
{ { Fact t1=new Fact(5);
this.n=n; this.n=n; Sum t2=new Sum(4);
} }
public void run() { public void run() { t1.start();
int fact=1; int sum=0; t2.start();
for(int i = 1; i <=n; i++) { for(int i = 1; i <=n; i++) {
fact=fact*i; sum=sum+i; }
} } }
System.out.println("Factorial System.out.println("Sum is:"+sum);
is:"+fact); }
} }
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Creating a Thread using Implementing the Runnable interface.

• The easiest way to create a thread is to create a class that implements the Runnable
interface and override run() method.

class RunnableDemo {
class NewThread implements Runnable{ public static void main(String args[]) {
public void run() { NewThread ob1=new NewThread();
for(int i = 0; i < 3; i++) { NewThread ob2=new NewThread();
System.out.println(Thread.currentThread(). NewThread ob3=new NewThread();
getName()+ ": " + i); Thread t1=new Thread(ob1); Thread-2: 0
} Thread t2=new Thread(ob2); Thread-2: 1
} Thread t3=new Thread(ob3); Thread-0: 0
Thread-0: 1
} t1.start(); Thread-1: 0
t2.start(); Thread-2: 2
t3.start(); Thread-0: 2
Thread-1: 1
}} Thread-1: 2

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


sleep()
• The sleep() method is used to pause the execution of a thread for a specified amount of
time.
• The sleep() method can throw an InterruptedException if the thread is interrupted while
sleeping.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 11


sleep() method
• Write a Java program that creates three threads. First thread displays “Good Morning”
every one second, the second thread displays “Hello” every two seconds and the third
thread displays “Welcome” every three seconds.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


sleep() method
class One extends Thread try{
{ System.out.println("Hello "); class ThreadEx
public void run() Thread.sleep(2000); {
{ } public static void main(String[]
for(int i=0;i<3;i++) catch(InterruptedException e){} args)throws InterruptedException
{ }}} {
try{ One t1=new One();
System.out.println("Good Morning"); class Three extends Thread Two t2=new Two();
Thread.sleep(1000); { Three t3=new Three();
} public void run() t1.start();
catch(InterruptedException e){ } { t2.start();
}}} for(int i=0;i<3;i++) t3.start(); Good Morning
{ }} Good Morning
class Two extends Thread try{ Good Morning
{ System.out.println("Wel come"); Hello
public void run() Thread.sleep(3000); } Hello
{ catch(InterruptedException e){ } Hello
for(int i=0;i<3;i++) }}} Wel come
{ Wel come
Wel come

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Thread Synchronization
• When two or more threads need access to a shared resource, synchronization ensures
that the resource will be used by only one thread at a time.
• Java Synchronization allows only one thread can access the shared resource at a given
point in time.

• You can synchronize your code in either of two ways

1. By Using Synchronized Method: 2. By Using Synchronized Block:

synchronized return type method ( parameters) synchronized(sync_object) {


{ // Access shared resources
//synchronized code }
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 14


Thread Synchronization

Create a Thread “BankAccount” using Thread class. Bob and Joy are having joint
account with an initial balance of 100000 and they both together allowed to withdraw.
Create one thread for each of them and concurrently perform withdrawal. Create a class
bankactivity with two methods “withdrawal and “balance”. Create a synchronized
withdrawal method so that While withdrawing no other process can be done.

Balance=balance-withdrawal_amount print “withdrawal completed” and balance


amount
if balance<withdrawal_amount print “Not enough in account to withdraw”

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 15


Thread Synchronization
class Bankactivity{ class BankAccount extends Thread{
int balance=100000; Bankactivity t;
synchronized void withdraw(int withdrawal_amount ){ int w_amount;
if(balance<withdrawal_amount){ BankAccount(Bankactivity t,int w_amount){
System.out.println(Thread.currentThread().getName()+": this.t=t;
Not enough money in account to withdraw"); this.w_amount=w_amount;
} }
else public void run(){
{ t.withdraw(w_amount);
System.out.println(Thread.currentThread().getName()
+":withdrawal completed" ); }
} public class Booking_Ex{
balance=balance-withdrawal_amount ; public static void main(String args[]){
} Bankactivity obj = new Bankactivity();t
} BankAccount t1=new BankAccount(obj,50000);
} BankAccount t2=new BankAccount(obj,60000);
t1.setName("Bob");
t2.setName("Joy");
Bob: withdrawal completed t1.start();
Joy: Not enough money in account to withdraw t2.start();
} }
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 16
Thread Synchronization
Consider the online ticket booking system for a cricket match. Suppose, there are 4
persons booking ticket at the same time. In this scenario, write a JAVA program that
creates 4 threads for 4 person and achieve synchronization with the help of following
details. Note that each person wants different number of tickets. Implement the
scenario where, if one thread is executing bookticket() method then other thread
should only be allowed to execute it after first thread completes.

The method bookticket() has this form: bookticket(String name, int numberoftickets).
In this method, check if tickets are available; if available then the particular person will
book that number of tickets otherwise print the message that there are no tickets for
booking. Update the number of tickets after booking. Consider initially
numberoftickets=8. Also, write down the output of the program with synchronization

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 17


Thread Synchronization
class Newthread extends Thread{
class Booking{ Booking t;
int available=8; int n;
void bookticket(String name, int numberoftickets){ String name;
synchronized(this){ Newthread(Booking t,String name,int n){
if(numberoftickets<=available){ this.t=t;
System.out.println(name+" this.name=name;
Booked:"+numberoftickets); this.n=n;
available=available-numberoftickets; }
} public void run(){
else t.bookticket(name,n);
System.out.println(name+"No tickets for booking"); public class Booking_Ex2{
} } }
public static void main(String args[]){
} Booking obj = new Booking();
} Newthread t1=new Newthread(obj,"Ram",5);
Newthread t2=new Newthread(obj,"Dev",2);
Newthread t3=new Newthread(obj,"Hav",4);
Newthread t4=new Newthread(obj,"Su",1);
t1.start();
t2.start();
t3.start();
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE t4.start(); 18
Thread Synchronization
Consider the Online Library Booking System for a VIT-AP University students to
reserve JAVA text books. Suppose, there are 4 students requesting JAVA text books at
the same time. In this scenario, write a JAVA program that creates 4 threads for 4
students and achieve synchronization with the help of following details. The method
bookrequest() has this form: bookrequest(String username, int requstedbookcount). In
this method, A check will be made to know the availability of books; if available then
the requested number of JAVA text books will be reserved for that particular person,
otherwise print the message “There are not enough JAVA text books for booking”.
Update the number of JAVA text books after each booking. The initial condition of
number of java books available is 4. Also, write down the output of the program with
synchronization.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 19


Thread Synchronization
class Student extends Thread {
class Library { Library lib;
int availableBooks=4; String username;
int requestedBookCount;
public synchronized void bookRequest(String username, int public Student(Library lib, String username, int requestedBookCo
requestedBookCount) { this.lib = lib;
if (availableBooks >= requestedBookCount) { this.username = username;
availableBooks -= requestedBookCount; this.requestedBookCount = requestedBookCount;
System.out.println(username + "booked " + }
requestedBookCount ); public void run() {
} lib.bookRequest(username, requestedBookCount);
else{ }
System.out.println("There are not enough text books for } public class Lib_Ex {
booking for" +username); public static void main(String[] args) {
} Library library = new Library();
}
} Student s1 = new Student(library, "Student1", 1);
Student s2 = new Student(library, "Student2", 2);
Student s3 = new Student(library, "Student3", 1);
Student s4 = new Student(library, "Student4", 2);

s1.start();
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 20
Inter Thread Communication
• In Java, interthread communication is a mechanism that allows threads to communicate
with each other by signaling or notifying each other about certain events or conditions.
• It is typically used when one thread needs to wait for another thread to complete a
certain task.
• Java provides a built-in mechanism for interthread communication through the wait(),
notify(), and notifyAll() methods.
• These methods can only be called from within a synchronized context.
• wait(): When a thread calls the wait() method on an object, it enters a waiting state
until another thread calls notify() or notifyAll() on the same object.
• notify(): The notify() method is used to wake up a single thread that is waiting on the
same object.
• notifyAll(): The notifyAll() method wakes up all threads that are waiting on the same
object.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 21


Inter Thread Communication
• Write a JAVA Program to achieve interthread communication with the
following scenario. A husband & wife located in different places so
they created a common account in a bank for depositing and
withdrawing amount. Consider withdraw and deposit threads to
perform withdraw and deposit operations on a shared bank account
using withdraw() and deposit() methods, respectively . While
withdrawing amount, if the available balance is less than the withdraw
amount then current thread should wait until the counter thread is
deposited the amount in the bank.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 22


Inter Thread Communication
class BankAccount { class Wife extends Thread {
int balance = 0; BankAccount account; public class BankApp {
public Wife(BankAccount account) { public static void main(String[] args) {
public synchronized void withdraw(int amount) { this.account = account; BankAccount account = new
while (balance < amount) { } BankAccount();
try { public void run() {
wait(); // Wait until the balance is sufficient account.withdraw(100); Husband h= new Husband(account);
} catch (InterruptedException e){ } } Wife w= new Wife(account);
} }
balance -= amount; h.setName("Husband");
System.out.println(Thread.currentThread().getName() + " w.setName("Wife");
withdrew: " + amount + ", Current Balance: " + balance);
} class Husband extends Thread { h.start();
public synchronized void deposit(int amount) { BankAccount account; w.start();
balance += amount; }
System.out.println(Thread.currentThread().getName() + " public Husband(BankAccount account) { }
deposited: " + amount + ", Current Balance: " + balance); this.account = account;
notify(); // Notify the waiting thread that an amount has }
been deposited
} public void run() {
account.deposit(200);
} }
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 23


Inter Thread Communication

• Implement a movie reservation system using interthread communication (ITC) in Java.


The system should allow multiple customer threads to book and cancel reservations
simultaneously. Ensure proper synchronization to avoid conflicts and race conditions.
Use wait(), notify() methods for interthread communication.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 24


class MovieReservationSystem { class CustomerBook extends Thread {
int availableSeats=5; MovieReservationSystem rs;
int seatsToBook;
public synchronized void book(int seats) { public class ReservationApp {
while (availableSeats < seats) { public CustomerBook(MovieReservationSystem rs, public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + " int seatsToBook) { MovieReservationSystem res = new
wants to book " + seats + " seats but only " + availableSeats + " this.rs = rs; MovieReservationSystem();
are available. Waiting for cancellation..."); this.seatsToBook = seatsToBook;
try { } CustomerBook customer1 = new
wait(); // Wait until seats are available CustomerBook(res, 4);
} catch (InterruptedException e) { @Override CustomerBook customer2 = new
Thread.currentThread().interrupt(); // Restore the public void run() { CustomerBook(res, 3);
interrupted status rs.book(seatsToBook); CustomerCancel customer3 = new
System.out.println(Thread.currentThread().getName() + } CustomerCancel(res, 2);
" was interrupted."); }
} customer1.setName("Customer1");
} class CustomerCancel extends Thread { customer2.setName("Customer2");
availableSeats -= seats; MovieReservationSystem rs; customer3.setName("Customer3");
System.out.println(Thread.currentThread().getName() + " int seatsToCancel;
booked " + seats + " seats. Remaining seats: " + availableSeats);
} public CustomerCancel(MovieReservationSystem customer1.start();
rs, int seatsToCancel) { customer2.start();
public synchronized void cancel(int seats) { this.rs = rs; customer3.start();
availableSeats += seats; this.seatsToCancel = seatsToCancel;
System.out.println(Thread.currentThread().getName() + " } }
cancelled " + seats + " seats. Available seats: " + availableSeats); }
notify(); // Notify a waiting thread that seats have been @Override
cancelled public void run() {
} rs.cancel(seatsToCancel);
} }
} SCOPE
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, 25
Inter Thread Communication
• Write a JAVA Program to achieve interthread communication with the following
scenario. A company stores the stock of goods and sells it whenever customers order
it. However, if the number of stock of goods is less than the customer order then the
company has to add the stock of goods. Consider customer_order as Thread1 and
add_stock as Thread2. There will two methods purchaseStock(int quantity) and
addStock(int quantity). Consider initial_quantity=30 and purchase_quantity=40. You
have to call purchaseStock() method by specifying quantity=40. In the purchaseStock()
method, check the initial_quantity; if it is less than purchasing quantity; then
Thread1(customer_order) will wait for Thread2(add_stock)) to complete and then
Thread 2 will notify to Thread1 about it.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 26


Inter Thread Communication
class Stock { class CustomerOrder extends Thread {
int quantity=30; Stock stock; public class itc {
public synchronized void purchaseStock(int purchaseQuantity) int purchaseQuantity; public static void main(String[] args) {
{ Stock stock = new Stock();
System.out.println("Customer order: " + purchaseQuantity); public CustomerOrder(Stock stock, int CustomerOrder t1 = new
if (quantity < purchaseQuantity) { purchaseQuantity) { CustomerOrder(stock, 40);
System.out.println("Not enough stock available. Waiting this.stock = stock; AddStock t2= new AddStock(stock,
for stock to be added"); this.purchaseQuantity = purchaseQuantity; 50);
try { } t1.start();
wait(); // Customer thread waits for stock to be added t2.start();
} catch (InterruptedException e) { public void run() { }}
// Handle interruption stock.purchaseStock(purchaseQuantity);
} } }
}
System.out.println("Processing customer order...");
quantity = quantity-purchaseQuantity; class AddStock extends Thread {
System.out.println("Remaining stock: " + quantity); Stock stock;
} int stockQuantity;
public synchronized void addStock(int stockQuantity) {
System.out.println("Adding stock: " + stockQuantity); public AddStock(Stock stock, int stockQuantity) {
quantity += stockQuantity; this.stock = stock;
System.out.println("Stock added. New quantity: " + this.stockQuantity = stockQuantity;
quantity); }
notify(); // Notify waiting customer thread public void run() {
} stock.addStock(stockQuantity);
} }
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 27


Problems
1. Create a method called printTable in Java that uses synchronization to
ensure that the multiplication table printing is thread-safe. This
method should print the multiplication table for a given number.
Demonstrate the thread-safety of this method by running multiple
threads that invoke printTable concurrently.

2. Write a class Message with a field message and methods getMessage()


and setMessage(). Use wait() and notify() to synchronize these
methods such that getMessage() waits until a message is set and
setMessage() notifies waiting threads.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 28


Write a Java class Counter with a private integer field count and a
synchronized method increment() that increments count by 1. Write a
main method to demonstrate the use of multiple threads incrementing
the counter concurrently.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 29

You might also like