0% found this document useful (0 votes)
16 views12 pages

Unit 2 Java (20-31)

The document provides an overview of multithreading in Java, explaining the concept of threads, their lifecycle, and how to create them using the Thread class or Runnable interface. It also discusses synchronization in Java, highlighting the importance of managing access to shared resources and the methods for inter-thread communication. Additionally, examples demonstrate the implementation of multithreading and synchronization in Java programs.

Uploaded by

dpsami11149
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)
16 views12 pages

Unit 2 Java (20-31)

The document provides an overview of multithreading in Java, explaining the concept of threads, their lifecycle, and how to create them using the Thread class or Runnable interface. It also discusses synchronization in Java, highlighting the importance of managing access to shared resources and the methods for inter-thread communication. Additionally, examples demonstrate the implementation of multithreading and synchronization in Java programs.

Uploaded by

dpsami11149
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/ 12

2.

3 Multithreading

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in


a single thread.

What is Thread in java

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path


of execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

A thread is executed inside the process. There is context-switching between the


threads. There can be multiple processes inside the OS, and one process can have
multiple threads.

Life cycle of a Thread (Thread States)

A thread in Java at any point of time exists in any one of the following states. A thread
lies only in one of the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
The diagram shown below represents various states of a thread at any instant in time.

States of Thread in its Lifecycle

Life Cycle of a Thread

There are multiple states of the thread in a lifecycle as mentioned below:


1. New Thread: When a new thread is created, it is in the new state. The thread has
not yet started to run when the thread is in this state. When a thread lies in the new
state, its code is yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In this
state, a thread might actually be running or it might be ready to run at any instant
of time. It is the responsibility of the thread scheduler to give the thread, time to
run.
A multi-threaded program allocates a fixed amount of time to each individual
thread. Each and every thread runs for a short while and then pauses and
relinquishes the CPU to another thread so that other threads can get a chance to
run. When this happens, all such threads that are ready to run, waiting for the CPU
and the currently running thread lie in a runnable state.
3. Blocked: The thread will be in blocked state when it is trying to acquire a lock but
currently the lock is acquired by the other thread. The thread will move from the
blocked state to runnable state when it acquires the lock.
4. Waiting state: The thread will be in waiting state when it calls wait() method or
join() method. It will move to the runnable state when other thread will notify or that
thread will be terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a
time-out parameter. A thread lies in this state until the timeout is completed or until
a notification is received. For example, when a thread calls sleep or a conditional
wait, it is moved to a timed waiting state.
6. Terminated State: A thread terminates because of either of the following reasons:

 Because it exits normally. This happens when the code of the thread has been
entirely executed by the program.
 Because there occurred some unusual erroneous event, like a segmentation
fault or an unhandled exception

Java Threads | How to create a thread in Java

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method
on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void suspend(): is used to suspend the thread(depricated).
6. public void resume(): is used to resume the suspended thread(depricated).
7. public void stop(): is used to stop the thread(depricated).
Runnable interface:

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().

1. public void run(): is used to perform action for a thread.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs
the following tasks:

Skip 10sPlay VideoForward Skip 10s

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

FileName: Multi.java

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

Output:

thread is running...
2) Java Thread Example by implementing Runnable interface

FileName: Multi3.java

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9. t1.start();
10. }
11. }

Output:

thread is running...

If you are not extending the Thread class, your class object would not be treated as a
thread object. So you need to explicitly create the Thread class object. We are passing
the object of your class that implements Runnable so that your class run() method may
execute.

Java provides built-in support for multithreaded programming. A multi-threaded 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.
When a Java program starts up, one thread begins running immediately. This is usually
called the main thread of our program because it is the one that is executed when our
program begins.

The main thread is created automatically when our program is started. To control it we
must obtain a reference to it. This can be done by calling the method currentThread(
) which is present in Thread class. This method returns a reference to the thread on
which it is called. The default priority of Main thread is 5 and for all remaining user
threads priority will be inherited from parent to child.
Example Java

// Create multiple threads.


class NewThread implements Runnable {
String name; // name of thread
Thread t;

NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
}

// This is the entry point for thread.


public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
} }

class MultiThreadDemo {
public static void main(String[] args) {
NewThread nt1 = new NewThread("One");
NewThread nt2 = new NewThread("Two");
NewThread nt3 = new NewThread("Three");

// Start the threads.


nt1.t.start();
nt2.t.start();
nt3.t.start();

try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}

System.out.println("Main thread exiting.");


} }
Synchronization in Java

Multi-threaded programs may often come to a situation where multiple threads try to
access the same resources and finally produce erroneous and unforeseen results.
Why use Java Synchronization?
Java Synchronization is used to make sure by some synchronization method that only
one thread can access the resource at a given point in time.

Java Synchronized Blocks

Java provides a way of creating threads and synchronizing their tasks using
synchronized blocks.
A synchronized block in Java is synchronized on some object. All synchronized blocks
synchronize on the same object and can only have one thread executed inside them at
a time. All other threads attempting to enter the synchronized block are blocked until
the thread inside the synchronized block exits the block.

Thread Synchronization in Java

Thread Synchronization is used to coordinate and ordering of the execution of the


threads in a multi-threaded program. There are two types of thread synchronization
are mentioned below:
 Mutual Exclusive
 Cooperation (Inter-thread communication in Java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing
data. There are three types of Mutual Exclusive mentioned below:
 Synchronized method.
 Synchronized block.
 Static synchronization.
Example of Synchronization
Below is the implementation of the Java Synchronization:
// A Java program to demonstrate working of
// synchronized.

import java.io.*;
import java.util.*;

// A Class used to send a message


class Sender {
public void send(String msg)
{
System.out.println("Sending\t" + msg);
try {
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}

// Class for send a message using Threads


class ThreadedSend extends Thread {
private String msg;
Sender sender;

// Receives a message object and a string


// message to be sent
ThreadedSend(String m, Sender obj)
{
msg = m;
sender = obj;
}

public void run()


{
// Only one thread can send a message
// at a time.
synchronized (sender)
{
// synchronizing the send object
sender.send(msg);
}
}
}
// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);

// Start two threads of ThreadedSend type


S1.start();
S2.start();

// wait for threads to end


try {
S1.join();
S2.join();
}
catch (Exception e) {
System.out.println("Interrupted");
}
}
Output
Sending Hi

Hi Sent
Sending Bye

Bye Sent
The output is the same every time we run the program.
Inter-thread Communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized


threads to communicate with each other.

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. It is implemented by following methods of Object class:

o wait()
o notify()
o notifyAll()

1) wait() method

The wait() method causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount of
InterruptedException time.

2) notify() method

The notify() method wakes up a single thread that is waiting on this object's monitor. If
any threads are waiting on this object, one of them is chosen to be awakened. The choice
is arbitrary and occurs at the discretion of the implementation.

Syntax:

1. public final void notify()


3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

Syntax:
1. public final void notifyAll()
Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:

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 amount){


System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount){


System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();

}}

Output:

going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

You might also like