Sie sind auf Seite 1von 22

MultiThreading in Java

Defining Threads

Applications Threads are used to


perform:

Parallelism and concurrent execution of


independent tasks / operations.
Implementation of reactive user interfaces.
Non blocking I/O operations.
Asynchronous behavior.
Timer and alarms implementation.

Threaded Applications

Modern Applications & Systems

Operating System Level

Application Level

Multitasking: multiple applications running at


once
Multithreading: multiple operations performed at
the same time

Bottom Line:

Illusion of concurrency

Threaded Applications

Modern Systems

Multiple applications run concurrently!


This means that there are multiple processes on
your computer
games
web & email

office automation

multimedia

Multitasking
Multitasking

pictures

A single threaded program


class ABC
{
.
public void main(..)
{

..
}

begin

body
end

}
5

Threaded Applications

Modern Systems

Applications perform many tasks at once!


This means that there are multiple threads within
a single process.
Background printing

GUI rendering

Application core logic

A Multithreaded Program
Main Thread

start

Thread A

start

start

Thread B

Thread C

Threads may switch or exchange data/results


7

Single and Multithreaded


Processes
threads are light-weight processes within a process
Single-threaded Process

Multi-threaded Process
Threads of
Execution

Multiple instruction stream


Single instruction stream Common
Address Space
8

Multithreaded Server: For Serving


Multiple Clients Concurrently

Modern Applications

Example: Multithreaded Web Server

Process Request Client 1

Web/FTP
server

Process Request Client 2


Client 1
Process Request Client N

Client 2

Client N

Threaded Applications

Modern Applications

Example: Internet Browser + Youtube


Video Streaming

Favorities, Share,
Comments Posting

Java Threads

Java has built in support for Multithreading


Synchronization
Thread Scheduling
Inter-Thread Communication:

currentThread
yield
sleep
resume

start
run
stop

setPriority
getPriority
suspend

Java Garbage Collector is a low-priority


thread.
11

Threading Mechanisms...

Create a class that extends the Thread class


Create a class that implements the Runnable
interface
Thread

MyThread

(objects are threads)


[a]

Runnable

Thread

MyClass

(objects with run() body)


[b]
12

1st method: Extending Thread


class

Create a class by extending Thread class and override


run() method:
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}

Create a thread:
MyThread thr1 = new MyThread();
Start Execution of threads:
thr1.start();
Create and Execute:
new MyThread().start();

13

An example
class MyThread extends Thread {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx1 {
public static void main(String [] args ) {
MyThread t = new MyThread();
t.start();
}
}

14

2nd method: Threads by


implementing Runnable interface

Create a class that implements the interface Runnable and


override run() method:

class MyThread implements Runnable


{
.....
public void run()
{
// thread body of execution
}
}

Creating Object:
MyThread myObject = new MyThread();

Creating Thread Object:


Thread thr1 = new Thread( myObject );

Start Execution:
thr1.start();

15

An example
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
t.start();
}
}

16

Life Cycle of Thread


new
start()
I/O completed

ready
notify()

waiting
wait()

resume()

Time expired/
interrupted

sleeping

blocked

dispatch

sleep()

running

suspend()
Block on I/O

completion

stop()

dead
17

Thread Priority

In Java, each thread is assigned priority, which


affects the order in which it is scheduled for
running. The threads so far had same default
priority (NORM_PRIORITY) and they are served
using FCFS policy.

Java allows users to change priority:

ThreadName.setPriority(intNumber)

MIN_PRIORITY = 1
NORM_PRIORITY=5
MAX_PRIORITY=10

18

Accessing Shared Resources

Applications access to shared resources need to


be coordinated.

Printer (two person jobs cannot be printed at the


same time)
Simultaneous operations on your bank account.
Can the following operations be done at the same
time on the same account?

Deposit()
Withdraw()
Enquire()

19

Online Bank: Serving Many


Customers and Operations
Internet
Internet
Bank
Bank Server
Client
Client 11

Bank
Bank Operator
Operator 11
Bank
Bank Local
Local Area
Area Network
Network

Client
Client 22

Bank
Bank Operator
Operator M
M
Client
Client N
N

Bank
Bank Database
Database

Shared Resources

If one thread tries to read the data and other


thread tries to update the same data, it leads to
inconsistent state.
This can be prevented by synchronising access
to the data.
Use synchronized method:

public synchronized void update()


{

}
21

facebook.com/apex.tgi
twitter.com/ApextgiNoida
pinterest.com/apextgi

22

Das könnte Ihnen auch gefallen