Top Banner
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad
23

Multithreading in Java

Feb 02, 2016

Download

Documents

sanam

Multithreading in Java. Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad. Outline. Introduction Process and Multi-tasking Thread Need for Multithreading Thread Support in Java Thread Scheduling Summary. Process. It is executable program in memory Process Properties - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Multithreading in Java

Multithreading in Java

Sameer Singh Chauhan

Lecturer, I. T. Dept.,

SVIT, Vasad

Page 2: Multithreading in Java

Outline

• Introduction

• Process and Multi-tasking

• Thread

• Need for Multithreading

• Thread Support in Java

• Thread Scheduling

• Summary

Page 3: Multithreading in Java

Process

- It is executable program in memory

- Process Properties- Address space- Own program counter, execution context- Each process may execute a different

program– May contain multiple threads

Page 4: Multithreading in Java

Thread

- It is a lightweight process, a single sequentially executed stream of instructions

- Properties- Shares address space with other threads– Communicate via shared access to data– Multiple threads in process execute same

program

Page 5: Multithreading in Java

Need for Multithreading

- Speed up the computation- Two threads each solve half of the problem and them

combine their results- Speedup happens only on multiprocessors

- Faster Response- One thread computes while another handles user

interface- One thread loads an image from Internet while

another performs computation

- Performing multiple tasks simultaneously - One thread does garbage collection while other

performs computation- Several thread performs animation simultaneously

Page 6: Multithreading in Java

Programming with Threads

• Concurrent programming– Writing programs divided into independent

tasks– Tasks may be executed in parallel on

multiprocessors

• Multithreading– Executing program with multiple threads in

parallel– Special form of multiprocessing

Page 7: Multithreading in Java

MultithreadingSingle Thread

Two Thread

Page 8: Multithreading in Java

Thread Support in Java

• Two approaches– Thread class– Runnable interface

Page 9: Multithreading in Java

Thread Class

public class Thread extends Object implements Runnable {

public Thread(); public Thread(String name); // Thread name public Thread(Runnable R); // Thread R.run() public Thread(Runnable R, String name);

public void run(); public void start(); // begin thread execution ...}

Page 10: Multithreading in Java

More Thread Class Methods

public class Thread extends Object { … public static Thread currentThread() public String getName() public void interrupt() public boolean isAlive() public void join() public void setDaemon() public void setName() public void setPriority() public static void sleep() public static void yield()}

Page 11: Multithreading in Java

Thread Creations in Java

1. Thread class– Extend Thread class and override the run method

Examplepublic class newThread extends Thread { public void run() { … // code for each thread }

}newThread T = new newThread() ;// To create a new thread

T.start(); // begin running the new thread

… // thread executing in parallel

Page 12: Multithreading in Java

Thread Creations in Java2. Runnable interface

– Create object implementing Runnable interface– Pass it to Thread object via Thread constructor

Examplepublic class newThread implements Runnable { public void run() { … // code for each thread }}Thread T = new Thread(new newThread); // To create a new thread

T.start(); // begin running the new thread… // thread executing in parallel

Page 13: Multithreading in Java

Thread Creations in Java

– Runnable is interface• So it can be multiply inherited

• Required for multithreading in applets

Page 14: Multithreading in Java

Thread States

• Java thread can be in one of these states– New – thread allocated & waiting for start()– Runnable – thread can begin execution– Running – thread currently executing– Blocked – thread waiting for event (I/O, etc.)– Dead – thread finished

• Transitions between states caused by– Invoking methods in class Thread

• new(), start(), yield(), sleep(), wait(), notify()…

– Other (external) events• Scheduler, I/O, returning from run()…

Page 15: Multithreading in Java

Thread States

• State diagram

runnable

scheduler

new

dead

running blocked

new start

terminateIO, sleep,wait, join

yield,time slice

notify, notifyAll,IO complete,

sleep expired,join complete

Page 16: Multithreading in Java

Thread Types

• Java threads types– User– Daemon

• Provide general services • Typically never terminate• Call setDaemon() before start()

• Program termination1. All user threads finish2. Daemon threads are terminated by JVM3. Main program finishes

Page 17: Multithreading in Java

Thread – Scheduling

• Scheduler– Determines which runnable threads to run– Can be based on thread priority– Part of OS or Java Virtual Machine (JVM)

• Scheduling policy– Nonpreemptive (cooperative) scheduling– Preemptive scheduling

Page 18: Multithreading in Java

Non-preemptive Scheduling

• Threads continue execution until – Thread terminates

– Executes instruction causing wait (e.g., IO)

– Thread volunteering to stop (invoking yield or sleep)

Page 19: Multithreading in Java

Preemptive Scheduling

• Threads continue execution until– Same reasons as non-preemptive scheduling

– Preempted by scheduler

Page 20: Multithreading in Java

Java Thread Example

public class newThread extends Thread { public void run() { for (int i = 0; i < 3; i++) System.out.println(i); try { sleep((int)(Math.random() * 8000)); // 8 secs } catch (InterruptedException e) { } } public static void main(String[] args) { new newThread().start(); new newThread().start(); System.out.println(“Finished"); }}

Page 21: Multithreading in Java

Java Thread Example – Output

• Possible outputs– 0,1,2,0,1,2,Done // thread 1, thread 2, main()

– 0,1,2,Done,0,1,2 // thread 1, main(), thread 2

– Done,0,1,2,0,1,2 // main(), thread 1, thread 2

– 0,0,1,1,2,Done,2 // main() & threads interleaved

Page 22: Multithreading in Java

Thread Synchronization

• To solve the problem of race condition (data races)

• Two ways in Java– Synchronized methods– Synchronized statements

Page 23: Multithreading in Java

Summary

– Thread is a lightweight process– Faster in execution– Saves memory– Reduces the response time– Scheduling a big problem