0% found this document useful (0 votes)
4 views26 pages

Java Threads

The document provides an overview of Java threads, explaining their definition, advantages, and disadvantages, as well as how to create and manage them in Java. It details the states of threads, methods for controlling thread execution, and synchronization techniques to manage access to shared resources. Additionally, it includes code examples demonstrating thread creation and exception handling in runnable implementations.

Uploaded by

vidya zope
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views26 pages

Java Threads

The document provides an overview of Java threads, explaining their definition, advantages, and disadvantages, as well as how to create and manage them in Java. It details the states of threads, methods for controlling thread execution, and synchronization techniques to manage access to shared resources. Additionally, it includes code examples demonstrating thread creation and exception handling in runnable implementations.

Uploaded by

vidya zope
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Java Threads

Vidya Zope
What is a Thread?
• Individual and separate unit of execution
that is part of a process
– multiple threads can work together to
accomplish a common goal
• Video Game example
– one thread for graphics
– one thread for user interaction
– one thread for networking
What is a Thread?
Video Game
Process

video networking
interaction
Advantages
• easier to program
– 1 thread per task
• can provide better performance
– thread only runs when needed
– no polling to decide what to do
• multiple threads can share resources
• utilize multiple processors if available
Disadvantage
• multiple threads can lead to deadlock
– much more on this later
• overhead of switching between threads
Threads Concept
Multiple
threads on
multiple
CPUs

Multiple
threads
sharing a
single CPU

6
Threads in Java
Creating threads in Java:

• Extend [Link] class


OR
• Implement [Link] interface

7
Threads in Java
Creating threads in Java:
• Extend [Link] class
– run() method must be overridden (similar to main
method of sequential program)
– run() is called when execution of the thread begins
– A thread terminates when run() returns
– start() method invokes run()
– Calling run() does not create a new thread
• Implement [Link] interface

8
States of Java Threads
• 4 separate states
– new: just created but not started
– runnable: created, started, and able to run
– blocked: created and started but unable to run
because it is waiting for some event to occur
– dead: thread has finished or been stopped
States of Java Threads

stop(),
start() end of run method
runnable

new dead
wait(), notify(),
I/O request, I/O completion,
suspend() resume()
blocked
Threads in Java
Creating threads in Java:
• Extend [Link] class
• Implement [Link] interface
 Create a Runnable implementer and implement run() method.
 Instantiate Thread class and pass the implementer to
the Thread, Thread has a constructor which accepts Runnable instance.
 Invoke start() of Thread instance, start internally calls run() of the
implementer. Invoking start(), creates a new Thread which executes
the code written in run().
 Calling run() directly doesn’t create and start a new Thread, it will run
in the same thread. To start a new line of execution, call start() on
the thread.

11
Creating Threads Example 1
class Output extends Thread {
private String toSay;
public Output(String st) {
toSay = st;
}
public void run() {
try {
for(int i=1;i<3;i++) {

[Link]([Link]().getName()+ toSay);
sleep(1000);
}
} catch(InterruptedException e) {
[Link](e);
}
}
}
Example 1 (continued)
class Program {
public static void main(String [] args) {
Output thr1 = new Output("Hello");
Output thr2 = new Output("There");
[Link]();
[Link]();
}
}

D:\javaprograms>javac [Link]
D:\javaprograms>java Program
Thread-1There
Thread-0Hello
Thread-1There
Thread-0Hello
Creating Threads Example 2
class Output implements Runnable {
private String toSay;
public Output(String st) {
toSay = st;
}
public void run() {
try {
for(;;) {
[Link](toSay);
[Link](1000);
}
} catch(InterruptedException e) {
[Link](e);
}
}
}
Example 2 (continued)
class Program {
public static void main(String [] args) {
Output out1 = new Output(“Hello”);
Output out2 = new Output(“There”);
Thread thr1 = new Thread(out1);
Thread thr2 = new Thread(out2);
[Link]();
[Link]();
}
}
public class RunnableDemo {

public static void main(String[] args)


{
[Link]("Main thread is- "
+ [Link]().getName());
Thread t1 = new Thread(new RunnableDemo().new
RunnableImpl());
[Link]();
}

private class RunnableImpl implements Runnable {

public void run()


{
[Link]([Link]().getName
()
+ ", executing run() method!");
}
}
} Main thread is- main
Thread-0, executing run() method!
What happens when Runnable
encounters an exception ?

Runnable can’t throw checked exception but RuntimeException can be


thrown from run().
Uncaught exceptions are handled by exception handler of the thread, if JVM
can’t handle or catch exceptions, it prints the stack trace and terminates the
flow.
D:\javaprograms>java RunnableDemo
Main thread is- main
Thread-0, executing run() method!
Must catch here!
[Link]
at RunnableDemo$[Link]([Link])
at [Link]([Link])
Exception in thread "Thread-0" [Link]: / by zero
at RunnableDemo$[Link]([Link])
at [Link]([Link])
private class RunnableImpl implements Runnable {
public void run()
{
[Link]([Link]().getName()
+ ", executing run() method!");
/**
* Checked exception can't be thrown, Runnable must
* handle checked exception itself.
*/
try {
int r = 1 / 0;
throw new ArithmeticException();
}
catch (Exception e) {
[Link]("Must catch here!");
[Link]();
}
Controlling Java Threads
• _.start(): begins a thread running
• wait() and notify(): for synchronization
– more on this later
• _.stop(): kills a specific thread (deprecated)
• _.suspend() and resume(): deprecated
• _.join(): wait for specific thread to finish
• _.setPriority(): 0 to 10 (MIN_PRIORITY to
MAX_PRIORITY); 5 is default (NORM_PRIORITY)
Java Thread Scheduling
• highest priority thread runs
– if more than one, arbitrary
• yield(): current thread gives up processor so
another of equal priority can run
– if none of equal priority, it runs again
• sleep(msec): stop executing for set time
– lower priority thread can run
Java Thread Example 1
class Job implements Runnable {
private static Thread [] jobs = new Thread[4];
private int threadID;
public Job(int ID) {
threadID = ID;
}
public void run() { do something }
public static void main(String [] args) {
for(int i=0; i<[Link]; i++) {
jobs[i] = new Thread(new Job(i));
jobs[i].start();
}
try {
for(int i=0; i<[Link]; i++) {
jobs[i].join();
}
} catch(InterruptedException e) { [Link](e); }
}
}
Java Thread Example 2
class Schedule implements Runnable {
private static Thread [] jobs = new Thread[4];
private int threadID;
public Schedule(int ID) {
threadID = ID;
}
public void run() { do something }
public static void main(String [] args) {
int nextThread = 0;
setPriority(Thread.MAX_PRIORITY);
for(int i=0; i<[Link]; i++) {
jobs[i] = new Thread(new Job(i));
jobs[i].setPriority(Thread.MIN_PRIORITY);
jobs[i].start();
}
try {
for(;;) {
jobs[nextThread].setPriority(Thread.NORM_PRIORITY);
[Link](1000);
jobs[nextThread].setPriority(Thread.MIN_PRIORITY);
nextThread = (nextThread + 1) % [Link];
}
} catch(InterruptedException e) { [Link](e); }
}
}
Synchronization in Java

• Synchronization in java is the capability to


control the access of multiple threads to any
shared resource.
• Java Synchronization is better option where
we want to allow only one thread to access
the shared resource.
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){ class MyThread2 extends Thread{
Table t;
[Link](n*i); MyThread2(Table t){
this.t=t;
try{ }
public void run(){
[Link](400); [Link](100);
}catch(Exception e){[Link](e);} }
}
}
class TestSynchronization1{
} public static void main(String args[]){
} Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
class MyThread1 extends Thread{ MyThread2 t2=new MyThread2(obj);
[Link]();
Table t; [Link]();
MyThread1(Table t){ }
}
this.t=t; D:\javaprograms>javac [Link]

} D:\javaprograms>java TestSynchronization1
public void run(){ 5
100
[Link](5); 200
10
} 300
15
} 400
20
500
25
Java 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.
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e) {[Link](e);}
}

}
}
Synchronized block in java

• Synchronized block can be void printTable(int n){


used to perform synchronized(this){//
synchronization on any specific synchronized block
resource of the method. for(int i=1;i<=5;i++){
• Synchronized block is used to [Link](n*i);
lock an object for any shared try{
resource. [Link](400);
• Scope of synchronized block is }catch(Exception e)
smaller than the method. {[Link](e);}
}
}
}

You might also like