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

Unit1

Uploaded by

mdahmerusmani
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)
3 views

Unit1

Uploaded by

mdahmerusmani
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/ 73

Unit 1

Contents

Concurrent Programming: Concept of threads, lifecycle of


threads, creating threads, Thread class, Runnable
interface, Thread synchronization, inter thread
communication – wait(), notify(), notifyAll() methods .
• Concurrency is the ability of a program to execute
several computations simultaneously.
• This can be achieved by distributing the
computations over the available CPU cores of a
machine or even over different machines within the
same network.
• To achieve a better understanding of parallel
execution, we have to distinguish between processes
and threads.
• Processes are an execution environment provided by
the operating system that has its own set of private
resources (e.g. memory, open files, etc.).
• Threads in contrast are processes that live within a
process and share their resources (memory, open
files, etc.) with the other threads of the process.
• A Thread is a very light-weighted process, or
we can say the smallest part of the process
that allows a program to operate more
efficiently by running multiple tasks
simultaneously.

• In order to perform complicated tasks in the


background, we used the Thread concept in
Java.

• All the tasks are executed without affecting


the main program.

• In a program or process, all the threads have


their own separate path for execution, so
each thread of a process is independent.
• Another benefit of using thread is that if a
thread gets an exception or an error at the time
of its execution, it doesn't affect the execution
of the other threads.

• All the threads share a common memory and


have their own stack, local variables and
program counter.

• When multiple threads are executed in parallel


at the same time, this process is known
as Multithreading.

• Example:used in software such as VLC,games


,Animation
In a simple way, a Thread is a:

•Feature through which we can perform


multiple activities within a single process.

•Lightweight process.

•Series of executed statements.

•Nested sequence of method calls.


Life cycle of a Thread (Thread States)

The life cycle of the thread in java is controlled by


JVM.

The java thread states are as follows:


1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated
Creating Thread

A thread is created either by "creating or implementing" the Runnable


Interface or by extending the Thread class. These are the only two ways
through which we can create a thread.

Thread Class
A Thread class has several methods and constructors which allow us to
perform various operations on a thread. The Thread class extends
the Object class. The Object class implements the Runnable interface. The
thread class has the following constructors that are used to perform various
operations.

•Thread()
•Thread(String name)
•Thread(Runnable r)
•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 milliseconds): 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 join(long milliseconds): waits for a thread to die
for the specified milliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the
thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the
thread.
10. public Thread currentThread(): returns the reference of
currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object
to temporarily pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(deprecated).
16. public void resume(): is used to resume the suspended
thread(deprecated).
17. public void stop(): is used to stop the thread(deprecated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or
user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been
interrupted.
22. public static boolean interrupted(): tests if the current thread has
been interrupted.
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().

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

Starting a thread:

start() method of Thread class is used to start a newly


created thread. It performs following
tasks:
1)A new thread starts(with new call stack).
2)The thread moves from New state to the Runnable state.
3)When the thread gets a chance to execute, its target run()
method will run.
Java Thread Example by extending Thread class :

class Multi extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}

Output:thread is running...
Extending the thread class :

We can make our thread by extending the Thread class of


java.lang.Thread class.

This gives us access to all the methods of the Thread. It


includes the following steps:

I. Declare the class as Extending the Thread class.


II. Override the "run()" method that is responsible for running
the thread.
III.Create a thread and call the "start()" method to instantiate
the Thread Execution.

Declaring the class


TheThread class can be declared as follows:
class MyThread extends Thread
{ ----------------------- ---------------------- ---------------------- ----
------------------
}
Overriding the method run()
The run() is the method of the Thread. We can override this
as follows:
public void run()
{
} ---------------- ---------------- ----------------
Starting the new Thread
To actually to create and run an instance of the thread class,
we must write the following:
MyThread a=new MyThread(); // creating the Thread
a.start();
// Starting the Thread
// extending Thread class
public class ThreadExample1 extends Thread {
// run() method to perform action for thread.(override run())
public void run()
{
int a= 10;
int b=12;
int result = a+b;
System.out.println("Thread started running..");
System.out.println("Sum of two numbers is: "+ result);
}
public static void main( String args[] )
{
// Creating instance of the class extend Thread class
ThreadExample1 t1 = new ThreadExample1();
//calling start method to execute the run() method of the
Thread class
t1.start();
}
}
Output:

Thread started running..


Sum of two numbers is :22
Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}

Output:thread is running...
Example program:
class x implements Runnable
{ //1 STEP
public void run()
{ //2 STEP
for(int i=0;i<=5;i++)
System.out.println("The Thread x is:"+i);
System.out.println("End of the Thread x");
}
}
class RunnableTest
{
public static void main(String args[])
{
x r=new x();
Thread threadx=new Thread(r);
threadx.start();
System.out.println("The end of the main thread");
}
}
Runnable interface is having following steps:

1)Implements the runnable interface

2)Override the run ()method

3)Create object of thread class and pass the


parameter in constructor

4)Start the thread or invoke the thread


When a Thread is ended

It is often very important to know which thread is ended. This helps to prevent
the main from terminating before the child Thread is terminating. To address
this problem "Thread" class provides two methods: 1) Thread.isAlive() 2)
Thread.join().
The general form of the "isAlive()" method is as follows:
final boolean isAlive();
This method returns the either "TRUE" or "FALSE" . It returns "TRUE" if the thread
is alive, returns "FALSE" otherwise.

While isAlive( ) is occasionally useful, the method that you will more commonly
use to wait for a thread to finish is called join( ), shown here:
final void join( ) throws InterruptedException
This method waits until the thread on which it is called terminates
Priority of a Thread (Thread Priority):

• Each thread have a priority.



• Priorities are represented by a number between
1 and 10.

• In most cases, thread schedular schedules the


threads according to their priority (known as
preemptive scheduling).

• But it is not guaranteed because it depends on


JVM specification that which scheduling it
chooses.
• In practice, the amount of CPU time that a thread
gets often depends on several factors besides its
priority.

• (For example, how an operating system implements


multitasking can affect the relative availability of
CPU time.)

• A higher-priority thread can also preempt a lower-


priority one.

• For instance, when a lower-priority thread is running


and a higher-priority thread resumes (from sleeping
or waiting on I/O, for example), it will preempt the
lower priority thread.
3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

• Default priority of a thread is 5 (NORM_PRIORITY).

• The value of MIN_PRIORITY is 1 and

• the value of MAX_PRIORITY is 10.


Example of priority of a Thread:

class TestMultiPriority1 extends


Thread{public void run(){
System.out.println("running thread name
is:"+Thread.currentThread().getName());
System.out.println("running thread priority
is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Need of Thread Synchronization?

• When we start two or more threads within a program,


there may be a situation when multiple threads try to
access the same resource and finally they can produce
unforeseen result due to concurrency issues.

• For example, if multiple threads try to write within a


same file then they may corrupt the data because one of
the threads can override data or while one thread is
opening the same file at the same time another thread
might be closing the same file.
• Key to synchronization is the concept of the monitor
(also called a semaphore).

• A monitor is an object that is used as a mutually


exclusive lock, or mutex. Only one thread can own a
monitor at a given time. When a thread acquires a
lock, it is said to have entered the monitor.

• All other threads attempting to enter the locked


monitor will be suspended until the first thread exits
the monitor.

• These other threads are said to be waiting for the


monitor. A thread that owns a monitor can reenter the
same monitor if it so desires.
• Let us try to understand the problem without
synchronization. Here, in the following example to threads
are accessing the same resource (object) to print the Table.

• The Table class contains one method, printTable(int ), which


actually prints the table. We are creating two Threads,
Thread1 and Thread2, which are using the same instance of
the Table Resource (object), to print the table.

• When one thread is using the resource, no other thread is


allowed to access the same resource Table to print the table.
class Table {
// Method to print the table, not synchronized
void printTable(int n) {
for(int i = 1; i <= 5; i++) {
// Print the multiplication result
System.out.println(n * i);
try {
// Pause execution for 400 milliseconds
Thread.sleep(400);
} catch(Exception e) {
// Handle any exceptions
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread {
Table t;
// Constructor to initialize Table object
MyThread1(Table t) {
this.t = t;
}
// Run method to execute thread
public void run() {
// Call printTable method with argument 5
t.printTable(5);
}
}
class MyThread2 extends Thread {
Table t;
// Constructor to initialize Table object
MyThread2(Table t) {
this.t = t;
}
// Run method to execute thread
public void run() {
// Call printTable method with argument 100
t.printTable(100);
}
}
class TestSynchronization1 {
public static void main(String args[]) {
// Create a Table object
Table obj = new Table();
// Create MyThread1 and MyThread2
objects with the same Table object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
// Start both threads
t1.start();
t2.start();
}
}
Output:

5
100
10
200
15
300
20
400
25
500
In the above output, it can be observed
that both the threads are simultaneously
accessing the Table object to print the
table. Thread1 prints one line and goes to
sleep, 400 milliseconds, and Thread1
prints its task.
Using the Java synchronized method
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.
The general form of the synchronized method is:
synchronized type method_name(para_list)
{
//body of the method
}
where synchronized is the keyword, method contains the type,
and method_name represents the name of the method, and
para_list indicate the list of the parameters.
class Table {
// Synchronized method to print the table
synchronized void printTable(int n) {
for(int i = 1; i <= 5; i++) {
// Print the multiplication result
System.out.println(n * i);
try {
// Pause execution for 400
milliseconds
Thread.sleep(400);
} catch(Exception e) {
// Handle any exceptions
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread {
Table t;
// Constructor to initialize Table object
MyThread1(Table t) {
this.t = t;
}
// Run method to execute thread
public void run() {
// Call synchronized method printTable with argument 5
t.printTable(5);
}
}
class MyThread2 extends Thread {
Table t;
// Constructor to initialize Table object
MyThread2(Table t) {
this.t = t;
}
// Run method to execute thread
public void run() {
// Call synchronized method printTable with argument 100
t.printTable(100);
}
}
public class TestSynchronization2 {
public static void main(String args[]) {
// Create a Table object
Table obj = new Table();
// Create MyThread1 and MyThread2 objects with the
same Table object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
// Start both threads
t1.start();
t2.start();
}
}
Output:

5
10
15
20
25
100
200
300
400
500
In the above output it can be observed that when Thread1 is
accessing the Table object, Thread2 is not allowed to access
it. Thread1 preempts the Thread2 from accessing the
printTable() method.

Note:
1. This way of communications between the threads
competing for same resource is called implicit
communication.
2. This has one disadvantage due to polling. The polling
wastes the CPU time. To save the CPU time, it is preferred to
go to the inter-thread communication.
Inter-Thread Communication
• If two or more Threads are communicating with each
other, it is called "inter thread" communication.

• Using the synchronized method, two or more threads


can communicate indirectly.

• Through, synchronized method, each thread always


competes for the resource.

• This way of competing is called polling. The polling


wastes the much of the CPU valuable time.
• The better solution to this problem is, just notify
other threads for the resource, when the current
thread has finished its task. This is explicit
communication between the threads.
Java addresses this polling problem, using via wait(), notify(), and
notifyAll() methods.

These methods are implemented as final methods in Object,


so all classes have them. All three methods can be called only
from within a synchronized context.

1] 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( ).
2] notify( ) wakes up a thread that called wait( ) on the same
object.
3] notifyAll( ) wakes up all the threads that called wait( ) on the
same object. One of the threads will be granted access.
These methods are declared within Object, as
shown here:

final void wait( ) throws InterruptedException


final void notify( )
final void notifyAll( )

Additional forms of wait( ) exist that allow you to


specify a period of time to wait.
Suspending, Blocking and Stopping Threads

Whenever we want stop a thread we can stop from running


using "stop()" method of thread class. It's general form will
be as follows:
Thread.stop();
This method causes a thread to move from running to dead
state. A thread will also move to dead state automatically
when it reaches the end of its method.

Blocking Thread
A thread can be temporarily suspended or blocked from
entering into the runnable and running state by using the
following methods:

• sleep() —blocked for specified time


• suspend() ----blocked until further orders
• wait() --blocked until certain condition occurs

These methods cause the thread to go into the blocked


state. The thread will return to the runnable state when
the specified time is elapsed in the case of sleep(), the
resume() method is invoked in the case of suspend(), and
the notify() method is called in the case of wait().
Daemon Threads

Daemon threads are low-priority threads that run in the


background, providing services to other threads or
performing tasks such as garbage collection. Daemon
threads automatically terminate when all non-daemon
threads in the program have finished execution.

Thread daemonThread = new Thread();


daemonThread.setDaemon(true); // Set as daemon thread
Thread Interruption

Java provides the interrupt() method to interrupt a


thread's execution, signalling it to stop its current
activities and terminate gracefully. Threads can check
their interrupted status using the isInterrupted() method
or catch InterruptedException to handle interruptions
appropriately.

Thread thread = new Thread();


thread.interrupt(); // Interrupt the thread
Conclusion

• In the world of Java programming, understanding the


thread concept is paramount for building responsive,
scalable, and efficient applications.

• Threads enable developers to leverage the full


potential of modern multicore processors by executing
multiple tasks concurrently.

• By mastering thread creation, lifecycle management,


synchronization, and thread pools, Java developers can
unlock the power of multithreading and develop high-
performance software solutions.
program for inter thread communication – wait(),
notify(), notifyAll() methods .
class TotalEarnings extends Thread
{
int total=0;
public void run()
{

for (int i=1;i<=10;i++)


{
total=total+100;
}
}

public class MovieBook1


{
public static void main(String[] args) throws InterruptedException
{
TotalEarnings te=new TotalEarnings();
te.start();
System.out.println("total earnings :"+te.total);
}
}
class TotalEarnings extends Thread
{
int total=0;
public void run()
{
synchronized(this)
{
for (int i=1;i<=10;i++)
{
total=total+100;
}
this.notify();
}
}

}
public class MovieBook
{
public static void main(String[] args) throws InterruptedException
{
TotalEarnings te=new TotalEarnings();
te.start();
synchronized(te)
{
te.wait();
System.out.println("total earnings :"+te.total);
}
}
}
// Two threads performing two tasks at a time.
public class MyThreadd extends Thread
{
// Declare a String variable to represent task.
String task;

MyThreadd(String task)
{
this.task = task;
}
public void run()
{
for(int i = 1; i <= 5; i++)
{
System.out.println(task+ " : " +i);
try {
Thread.sleep(1000); // Pause the thread execution for
1000 milliseconds.
} catch(InterruptedException ie) {
System.out.println(ie.getMessage());
}
} // end of for loop.
} // end of run() method.
public static void main(String[] args)
{
// Create two thread objects to represent two tasks.
// Passing task as an argument to its constructor.
MyThreadd th1 = new MyThreadd("Cut the ticket");
MyThreadd th2 = new MyThreadd("Show your seat number");

// Create two objects of Thread class and pass two objects as


parameter to constructor of Thread class.
Thread t1 = new Thread(th1);
Thread t2 = new Thread(th2);
t1.start();
t2.start();
}
}
Multiple Threads Acting on Single Object

public class MultipleThread implements Runnable


{
String task;
MultipleThread(String task)
{
this.task = task;
}
public void run()
{
for(int i = 1; i <= 5; i++)
{
System.out.println(task+ ":" +i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
Thread nThread = Thread.currentThread();
System.out.println("Name of thread: " +nThread);

// Multiple child threads acting on single object.


MultipleThread mt = new MultipleThread("Hello Java");
Thread t1 = new Thread(mt);
Thread t2 = new Thread(mt);
Thread t3 = new Thread(mt);
t1.start();
t2.start();
t3.start();

int count = Thread.activeCount();


System.out.println("No of active threads: " +count);
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy