OCPJP Threads

23
Threads

Transcript of OCPJP Threads

Page 1: OCPJP Threads

Threads

Page 2: OCPJP Threads

Table of Contents

• Defining, Instantiating and Starting Threads• Defining a Thread• Instantiating a Thread• Starting a Thread

• Thread States and Transitions• Thread States• Preventing Thread Execution• Sleeping• Creating a Thread and putting it to Sleep• Thread priorities and yield()

• Synchronizing Code• Synchronization and Locks• Synchronizing a Block of Code• Thread Deadlock

• Thread Interaction• Using wait(), notify(), notifyAll( )

Page 3: OCPJP Threads

Defining, Instantiating and Starting Threads• In Java, ‘Thread’ means two different things:• An instance of class java.lang.Thread (just an object)• A thread of execution (a light-weight process that has its own

call stack)• When it comes to threads, very little is guaranteed.• The exam expects the developer to know what is and

what is not guaranteed behavior when a block of code, involving threads, is executed.

Page 4: OCPJP Threads

Defining Threads

Two ways of defining a thread1. Extending java.lang.Thread

public class MyThread extends Thread{public void run(){ System.out.println(“I am running by extending Thread class”); }}

2. Implementing java.lang.Runnablepublic class MyRunnable implements Runnable{public void run(){System.out.println(“I am running by implementing Runnable interface”); }}

Page 5: OCPJP Threads

Instantiating Threads

Two ways of instantiating a threadUsing Thread Object

MyThread t=new MyThread(); //If you extend Thread class

Using Runnable Interface

MyRunnable r=new MyRunnable();Thread t=new Thread(r); //Passing your Runnable to the Thread

Page 6: OCPJP Threads

Exam Watch!!• Will this compile?

class MyThread extends Thread{

public void run(){ System.out.println(“Run-method with no parameter”); }public void run(String s){ System.out.println(“Run-method with parameter:”+s); }

}

• Is this legal?

public class TestThreads{ public static void main(String[] args) {

MyRunnable r=new MyRunnable(); Thread t1=new Thread(r); Thread t2=new Thread(r); Thread t3=new Thread(r);

} }

Page 7: OCPJP Threads

Thread Constructors• Thread()• Thread(Runnable target)• Thread(String name)• Thread(Runnable target, String name)

Page 8: OCPJP Threads

Starting a thread

• A thread is started by calling the start() method as t.start().

• Unless this method is called, ‘t’ remains to be just an object of class java.lang.Thread in ‘new’ state.

• When the thread is ‘started’, following background activities take place:• A new thread of execution starts, called new call stack• The thread moves from ‘new’ to ‘runnable’ (not ‘running’) state• When the thread gets a chance to execute, it executes the run() method.

• Once a thread is started, it cannot be started again. It will cause an IllegalThreadStateException.

Page 9: OCPJP Threads

Thread states and transitions• New

• A thread instance is created, but start() method is not called. The thread is not alive.

• Runnable• A Thread first enters runnable state when the start() method is invoked• Thread is eligible to run, but not selected by the scheduler.• Thread returning from waiting/blocked/sleeping state comes to this state• Thread is considered alive.

• Running• Thread selected by scheduler for execution from the runnable pool.

• Waiting/Blocked/Sleeping• Enters this state waiting for a resource• Thread’s run code causes it to wait (obj.wait())• Thread’s run code causes it to sleep (t.sleep())• Still considered alive.

• Dead• Thread is dead when the run() method completes.• Dead thread cannot be started again using start(). That would cause a runtime exception.

Page 10: OCPJP Threads

Thread states• Thread state diagram

Page 11: OCPJP Threads

Preventing thread executionsleep() method• Static method• Throws InterruptedException; must always be present in a try/catch

block. • After completing sleep, thread returns to runnable state, not

running.• Not guaranteed that the thread would start executing after specified

number of milliseconds. Eg:

public void run(){try{ Thread.sleep(5*60*1000); }catch(InterruptedException ex) {}

}

Page 12: OCPJP Threads

Thread priorities and yield()• Each thread runs with a priority numbered between 1 to 10, range of

values may vary across JVMs.

• Most JVMs follow pre-emptive priority-based scheduling

• In most cases, running thread has equal or greater priority than the

highest priority threads in the runnable pool.

• yield() method • A thread calling yield() method agrees to move from running to runnable state and allow other

threads of same or higher priority to execute

• Not guaranteed that the scheduler would necessarily pick the thread to be moved to runnable

• A call to yield() method never causes a thread to sleep/wait/block, only moves it to runnable.

Page 13: OCPJP Threads

join() method• Non-static method• Causes one thread to join to the end of another.• Eg:

MyThread t=new MyThread();t.start();t.join();

• The join() method says ‘Join me (the current thread, main thread if the code in main method) to the end of t, so that t must finish before I (the current thread) can run again.’

Page 14: OCPJP Threads

Synchronization CodeRace condition

• Multiple threads can access the same resource and produce corrupted data in an atomic operation.

Page 15: OCPJP Threads

Synchronization Code• synchronized keyword

• Methods or blocks of code can be synchronized; not variables or classes.

• Each object, in Java, has an (only one) associated lock.

• A thread can execute synchronized block of code only if it has a lock on the object (on which

the method is to be called).

• A thread going to sleep does not release locks acquired by it.

• A class can have both synchronized methods and non-synchronized methods.• A thread can acquire more than one lock at the same time.

Page 16: OCPJP Threads

Synchronization Code• Methods of synchronization

• Synchronized method

public synchronized void doStuff(){ System.out.println(“synchronized”);}

• Synchronized block of code

public void doStuff{

System.out.println(“Not synchronized”);

synchronized(this)

{System.out.println(“Synchronized”);}

}

• Difference: When a method is synchronized, object’s lock must be acquired. When the block is

synchronized, you can specify which object’s lock you want the thread to acquire.

Page 17: OCPJP Threads

Synchronization Code• Synchronization of static methods

• Static methods of a class can be synchronized.

• Every class loaded in JVM has a corresponding instance of class java.lang.Class.

• To execute a synchronized static method, thread must acquire a lock on this ‘class’ instance.

• Two ways to synchronize static methods:

public static synchronized void doStuff(){ System.out.println(“synchronized”);}

public void doStuff

{

System.out.println(“Not synchronized”);

synchronized(MyClass.class)

{System.out.println(“Synchronized”);}

}

Page 18: OCPJP Threads

Synchronization Code

• Synchronization and blocking

• If a thread t1 needs a lock to continue and if the lock is already acquired by another thread t2, the thread t1

is blocked.

• Threads executing non-synchronized methods in same class will not block each other.

• Threads executing static synchronized methods will always block each other. Both block on the Class instance.

• A synchronized static and non-synchronized methods never block each other.

• Threads locking on same object would block each other for synchronized blocks. Threads locking on different

objects would not.

Page 19: OCPJP Threads

Synchronization Code• Thread-safe classes

• A class that has been carefully synchronized to protect its data is thread-safe.

• StringBuffer and StringBuilder are identical classes; StringBuffer has synchronized methods

whereas StringBuilder does not.

• Thread deadlock

• Two or more threads are blocked with each waiting for another to release a lock.

Page 20: OCPJP Threads

Synchronization CodeExample of deadlock

private Resource resourceA = new Resource(); private Resource resourceB = new Resource(); public int read() { synchronized(resourceA) { // May deadlock here synchronized(resourceB) { return resourceB.value + resourceA.value; } } } public void write(int a, int b) { synchronized(resourceB) { // May deadlock here synchronized(resourceA) { resourceA.value = a; resourceB.value = b; } } }

Page 21: OCPJP Threads

Thread interaction• wait(),notify() and notifyAll() are methods of class Object and not Thread class or Runnable

interface.

• These methods must be called from a synchronized context only.

• A thread cannot invoke these methods on an object if it does not have its lock. Otherwise, it would

cause an IllegalMonitorState exception.

• When the wait() method is invoked on an object, the thread executing that code gives up its lock

on the object immediately.

• When notify() is called, that doesn’t mean the thread gives up its lock at that moment, but only

after completion of the synchronized code.

• If there are many threads waiting for the lock on an object, notifyAll() method could be used to

notify all the methods which then compete to get the lock on the object.

Page 22: OCPJP Threads

Methods of Thread class Method Description

start() Starts the thread

run() Runs the job assigned to thread

setName() Assign a name to identify the thread

getName() Get the name assigned to the thread

getId() Returns a positive, unique, long number that guarantees to uniquely identify the thread

sleep(long millis) Causes the thread to sleep for minimum of ‘millis’ milliseconds

yield() Allows other threads of same or higher priority to execute

join() Makes the current thread to wait for this thread to complete

setPriority(int newPriority) Sets the priority for the thread in the range Thread.MIN_PRIORITY and Thread.MAX_PRIORITY

Page 23: OCPJP Threads

Q&A