Multitasking Multitasking allows several activities to occur concurrently on the computer. A...

51
THREADS

Transcript of Multitasking Multitasking allows several activities to occur concurrently on the computer. A...

Threads

Threads

MultitaskingMultitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitaskingProcess-based multitaskingprocess-based multitasking, which allows processes(i.e., programs) to run concurrently on the computer. A familiar example is running the spreadsheet program while also working with the word-processor.Thread-based multitaskingThread-based multitasking, which allows parts of the same program to run concurrently on the computer. A familiar example is a wordprocessor that is printing and formatting text at the same timeOverview of ThreadsA thread is an independent sequential path of execution within a program. Many threads can run concurrently within a program. At runtime, threads in a program exist in a common memory space and can, therefore, share both data and code (i.e. they are lightweight compared to processes). They also share the process running the program.

User Threads/Daemon ThreadsThe runtime environment distinguishes between user threads and daemon threads.As long as a user thread is alive, the JVM does not terminate. A daemon thread is at the mercy of the runtime system: it is stopped if there are no more user threads running, thus terminating the program. Daemon threads exist only to serve user threads.The Main ThreadWhen a standalone application is run, a user thread is automatically created to execute the main() method of the application. This thread is called the main thread.If no other user threads are spawned, the program terminates when the main() method finishes executing.Thread CreationA thread in Java is represented by an object of the Thread class. implementing threads is achieved in one of two ways: Implementing the java.lang.Runnable interface Extending the java.lang.Thread classExtending java.lang.ThreadThe simplest way to define code to run in a separate thread is to Extend the java.lang.Thread class. Override the run() method.It looks like this:class MyThread extends Thread {public void run() {System.out.println("Important job running in MyThread");}}The overloaded run(String s) method will be ignored by the Thread class unless you call it yourself. The Thread class expects a run() method with no arguments,

class MyThread extends Thread {public void run() {System.out.println("Important job running in MyThread");}public void run(String s) {System.out.println("String in run is " + s);}}Implementing the Runnable InterfaceWhen Class has extends different super class then class cant extends Thread class. Therefore class can implements the Runnable interface to create a thread.The Runnable interface has the following specification, comprising one abstract method declaration:public interface Runnable {void run();}public class RunnableThreadTest implements Runnable{ @Override public void run() { System.out.println(Runnable Thread Test); } public static void main(String[] args) { RunnableThreadTest runnable = new RunnableThreadTest(); Thread t1 = new Thread(runnable); t1.start(); }}Run()/Start() methodsRun method execute when calling to start method.MyThread t = new MyThread();t.start();If call t.run() method called then thread will not create. Just method calling only.Start() method cannot call same thread object more than once time. Then java.lang.IllegalThreadStateException pop up.

Thread SchedulerThe thread scheduler is the part of the JVM that decides which thread should run at any given moment, and also takes threads out of the run state. Assuming a single processor machine, only one thread can actually run at a time. Only one stack can ever be executing at one time.The order in which runnable threads are chosen to run is not guaranteed.Thread States and TransitionsA thread can be only in one of five states. New This is the state the thread is in after the Thread instance has been created, but the start() method has not been invoked on the thread. It is a live Thread object, but not yet a thread of execution. At this point, the thread is considered not alive.

Thread States and Transitions Runnable This is the state a thread is in when it's eligible to run, but the scheduler has not selected it to be the running thread. A thread first entersthe runnable state when the start() method is invoked, but a thread can also return to the runnable state after either running or coming back from a blocked, waiting, or sleeping state. When the thread is in the runnable state, it is considered alive.Thread States and Transitions Running . This is the state a thread is in when the thread scheduler selects it (from the runnable pool) to be the currently executing process. A thread can transition out of a running state for several reasons.

Thread States and TransitionsNot Runnable(Waiting/blocked/sleeping) This is the state a thread is in when it's noteligible to run. This is really three states combined into one,but they all have one thing in common: the thread is still alive, but is currently not eligible to run. In other words, it is not runnable. May be blocked waiting for a resource May be sleeping because the thread's run code tells it to sleep for some period of time, May be waiting, because the thread's run code causes it to waitThread States and TransitionsThread States and Transitions Dead A thread is considered dead when its run() method completes. It may still be a viable Thread object, but it is no longer a separate thread ofexecution. Once a thread is dead, it can never be brought back to life! (The whole "I see dead threads" thing.) If you invoke start() on a dead Thread instance, you'll get a runtime (not compiler) exception.

Thread ConstructorsThread()Thread(Runnable target)Thread(Runnable target, String name)Thread(String name)Thread(ThreadGroup group, Runnable target)Thread(ThreadGroup group, Runnable target, String name)Thread(ThreadGroup group, Runnable target, String name, long stackSize)Thread(ThreadGroup group, String name)java.lang.Thread Methodspublic static void sleep(long millis) throws InterruptedExceptionpublic static void yield()public final void join() throws InterruptedExceptionpublic final void setPriority(int newPriority)

Note that both sleep() and join() have overloaded versions not shown here.java.lang.Object MethodsEvery class in Java inherits the following three thread-related methods:public final void wait() throws InterruptedExceptionpublic final void notify()public final void notifyAll()

The wait() method has three overloaded versionsDeprecated Thread class Methodspublic void destroy()public final void resume()public final void stop()public final void suspend()public static void sleep(long m) sleep() method in the Thread class will cause the currently running thread to temporarily pause its execution and transit to the Not Runnable state. The thread will sleep for at least the time specified in its argument.Before transitioning to the Ready to-run state where it takes its turn to run again.Throws InterruptedException.sleep() time is not a guarantee that the thread will start running again as soon as the time expires and the thread wakes.public static void sleep(long m)

public class SleepingThreadTest extends Thread { public void run() { try { System.out.println("Thread Start"); Thread.sleep(10000); } catch (InterruptedException ex) { }} public static void main(String[] args) { SleepingThreadTest obj1 = new SleepingThreadTest(); obj1.start(); SleepingThreadTest obj2 = new SleepingThreadTest(); obj2.start(); obj2.start(); }}public static void yield()yield() method defined in the Thread class, may cause the current thread in the Running state to transit to the Ready-to-run state.It is possible that if there are no threads in theReady-to-run state, this thread can continue executing. If there are other threads in the Ready-to-run state, their priorities can influence which thread gets to execute.public static void yield()

Thread's PriorityPriorities are set using a positive integer, usually between 1 and 10, and the JVM will never change a thread's priority. Although the default priority is 5.Use setPriority(int value) method to set the priority.Thread class has the three following constants (static final variables) that define the range of thread priorities.Thread.MIN_PRIORITY (1)Thread.NORM_PRIORITY (5)Thread.MAX_PRIORITY (10)

Thread's PriorityFooRunnable r = new FooRunnable();Thread t = new Thread(r);t.setPriority(8);t.start();public final void join()The non-static join() method of class Thread lets one thread "join onto the end of another thread. If you have a thread B that can't do its work until another threadA has completed its work, then you want thread B to "join" thread A. This means that thread B will not become runnable until A has finished (and entered the dead state).Thread t = new Thread();t.start();t.join();public final void join()t.join() means "Join me (the current thread) to the end of t, so that t must finish before I (the current thread) can run again.Throws InterruptedException.

Sleep()/yield()/join() A call to sleep() Guaranteed to cause the current thread to stop executingfor at least the specified sleep duration (although it might be interrupted. Before its specified time). A call to yield() Not guaranteed to do much of anything, althoughtypically it will cause the currently running thread to move back to runnable. so that a thread of the same priority can have a chance. A call to join() Guaranteed to cause the current thread to stop executinguntil the thread it joins with (in other words, the thread it calls join().Synchronizing CodeThreads share the same memory space, i.e., they can share resources. How ever, there are critical situations where it is desirable that only one thread at a time has access to a shared resource. For example, crediting and debiting a shared bank account concurrently among several users without proper discipline, will jeopardizethe integrity of the account data. Java provides high-level concepts for synchronization in order to control access to shared resources.private void makeWithdrawal(int amt) {if (acct.getBalance() >= amt) {System.out.println(Thread.currentThread().getName()+ " is going to withdraw");try { Thread.sleep(500);} catch(InterruptedException ex) { }acct.withdraw(amt);System.out.println(Thread.currentThread().getName()+ " completes the withdrawal");} else {System.out.println("Not enough in account for "+ Thread.currentThread().getName()+ " to withdraw " + acct.getBalance());}}Non Synchronize MethodLocksA lock (also called a monitor) is used to synchronize access to a shared resource. A lock can be associated with a shared resource. Threads gain access to a shared resource by first acquiring the lock associated with the resource. At any given time,at most one thread can hold the lock and thereby have access to the shared resource.Synchronization and LocksRemember the following key points about locking andsynchronization:

Only methods (or blocks) can be synchronized, not variables or classes. Each object has just one lock. Not all methods in a class need to be synchronized. A class can have both synchronized and non-synchronized methods.Synchronization and Locks If two threads are about to execute a synchronized method in a class, and both threads are using the same instance of the class to invoke the method, only one thread at a time will be able to execute the method. The other thread will need to wait until the first one finishes its method call. In other words, once a thread acquires the lock on an object, no other thread can enter any of the synchronized methods in that class (for that object).Synchronized method private synchronized void makeWithdrawal(int amt) {if (acct.getBalance() >= amt) {System.out.println(Thread.currentThread().getName() +" is going to withdraw");try { Thread.sleep(500);} catch(InterruptedException ex) { }acct.withdraw(amt);System.out.println(Thread.currentThread().getName() +" completes the withdrawal");} else {System.out.println("Not enough in account for "+ Thread.currentThread().getName()+ " to withdraw " + acct.getBalance());}}Synchronized method synchronized methods prevent more than one thread from accessing an object's critical method code simultaneously. You can use the synchronized keyword as a method modifier, or to start a synchronized block of code. To synchronize a block of code (in other words, a scope smaller than the whole method), you must specify an argument that is the object whose lockyou want to synchronize on.Synchronized method While only one thread can be accessing synchronized code of a particularinstance, multiple threads can still access the same object's unsynchronized code. When a thread goes to sleep, its locks will be unavailable to other threads. static methods can be synchronized, using the lock from thejava.lang.Class instance representing that class.Synchronized Block Examplepublic void doStuff() {synchronized(this) {System.out.println("synchronized");}}Static Method Synchronized Block ExampleIf the method is defined in a class called MyClass, the equivalent code is as follows:public static int getCount() {synchronized(MyClass.class) {return count;}}

Static Method Synchronized Block ExampleMyClass.class thing? That's called a class literal. It's aspecial feature in the Java language that tells the compiler (who tells the JVM): goand find me the instance of Class that represents the class called MyClass. Static Method Synchronized Block ExampleYou can also do this with the following code:public static void classMethod() {

Class cl = Class.forName("MyClass");synchronized (cl) {// do stuff}}Communicating with Objects by Waiting and Notifying The wait() method lets a thread say, "there's nothing for me to do now, soput me in your waiting pool and notify me when something happens that Icare about." Basically, a wait() call means "wait me in your pool," or "addme to your waiting list." The notify() method is used to send a signal to one and only one of thethreads that are waiting in that same object's waiting pool. The notify() method can NOT specify which waiting thread to notify.Communicating with Objects by Waiting and Notifying The method notifyAll() works in the same way as notify(), only it sendsthe signal to all of the threads waiting on the object. All three methodswait(), notify(), and notifyAll()must be called from within a synchronized context! A thread invokes wait() or notify() on a particular object, and the thread must currently hold the lockon that object.Thank You