We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46
Chapter 5
Multithreading
1 Ch-5: MultiThreading 03/01/2024
Introduction One of the powerful features of Java is its built-in support for multithreading the concurrent running of multiple tasks within a program. In many programming languages, you have to invoke system- dependent procedures and functions to implement multithreading. This chapter introduces the concepts of threads and how to develop multithreading programs in Java. A Web browser is an example of a multithreaded application. Within a typical browser, you can scroll a page while it's downloading an applet or an image, play animation and 2 sound concurrently, etc. Ch-5: MultiThreading 03/01/2024 …Con All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!" or sorts a list of names or computes a list of prime numbers. These are sequential programs. That is, each has a beginning, an execution sequence, and an end. At any given time during the runtime of the program, there is a single point of execution.
A thread is similar to the sequential programs described
previously. A single thread also has a beginning, a sequence, and an end. At any given time during the runtime of the thread, there is a single point of execution. However, a thread itself is not a 3 program; a thread cannot run on its own. Rather, it runs Ch-5: MultiThreading within 03/01/2024 …Con You are probably familiar with multitasking: the ability to have more than one program working at what seems like the same time. For example, you can print while editing or sending a fax.
Multithreaded programs extend the idea of multitasking by
taking it one level: individual programs will appear to do multiple tasks at the same time. Each task is usually called a thread which is short for thread of control. Programs that can run more than one thread at once are said to be multithreaded.
4 Ch-5: MultiThreading 03/01/2024
Multitasking and Multithreading Multitasking: refers to a computer's ability to perform multiple jobs concurrently more than one program are running concurrently, e.g., UNIX, Windows Multithreading: A thread is a single sequence of execution within a program refers to multiple threads of control within a single program each program can run multiple threads of control within it. Ex: in a Web browser we may do the following tasks at the same time: 1. scroll a page, 2. download an applet or image, 3. play sound, 4 print a page. A thread is a single sequential flow of control within a program. 5 Ch-5: MultiThreading 03/01/2024 …Con A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.
Multithreading enables you to write very efficient programs
that make maximum use of the CPU, because idle time can be kept to a minimum. Helps to perform different tasks in a single program
6 Ch-5: MultiThreading 03/01/2024
Threads and Processes CPU
main
run
Process 1 Process 2 Process 3 Process 4
GC
7 Ch-5: MultiThreading 03/01/2024
…Con Threads are sometimes referred to as lightweight processes. Like processes, threads are independent, concurrent paths of execution through a program, and each thread has its own stack, its own program counter, and its own local variables. However, threads within a process are less insulated from each other than separate processes are. They share memory, file handles, and other per-process state. The Java thread facility and API is deceptively simple.
8 Ch-5: MultiThreading 03/01/2024
Every Java program uses threads Every Java program has at least one thread -- the main thread. When a Java program starts, the JVM creates the main thread and calls the program's main()method within that thread. The JVM also creates other threads that are mostly invisible to you – for example, Threads associated with garbage collection, object finalization, and other JVM housekeeping tasks. Other facilities create threads too, such as the AWT (Abstract Windowing Toolkit) or Swing UI toolkits, servlet containers, application servers, and RMI (Remote 9 Method Invocation). Ch-5: MultiThreading 03/01/2024 …Con // Controlling the main Thread. System.out.println(n); class CurrentThreadDemo { Thread.sleep(1000); public static void main(String } args[]) { } catch (InterruptedException e) Thread t = { Thread.currentThread(); System.out.println("Main System.out.println("Current thread interrupted"); thread: " + t); } // change the name of the thread } t.setName("My Thread"); } System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) {
10 Ch-5: MultiThreading 03/01/2024
Why use threads? If you use Swing, servlets, RMI, or Enterprise JavaBeans (EJB) technology, you may already be using threads without realizing it. Some of the reasons for using threads are that they can help to: 1. Make the UI more responsive 2. Take advantage of multiprocessor systems 3. Simplify modeling 4. Perform asynchronous or background processing
11 Ch-5: MultiThreading 03/01/2024
Simple, but sometimes risky While the Java thread facility is very easy to use, there are several risks you should try to avoid when you create multithreaded programs. When multiple threads access the same data item, such as a static field, an instance field of a globally accessible object, or a shared collection So, to make sure that they coordinate their access to the data so that both see a consistent view of the data and neither steps on the other's changes. The Java language provides two keywords for this purpose: synchronized and volatile.
12 Ch-5: MultiThreading 03/01/2024
… When accessing variables from more than one thread, you must ensure that the access is properly synchronized. For simple variables, it may be enough to declare the variable volatile, but in most situations, you will need to use synchronization. If you are going to use synchronization to protect access to shared variables, you must make sure to use it everywhere in your program where the variable is accessed.
13 Ch-5: MultiThreading 03/01/2024
Thread States Thread has many different state through out its life. Newborn State 1. 2. Runnable State 3. Running State 4. Blocked State 5. Dead State Thread should be in any one state of the above and it can be move from one state to another by different methods and ways.
14 Ch-5: MultiThreading 03/01/2024
The Thread class constructor Thread() : creates a new Thread object Thread(String name): creates a new Thread object with the specified name Thread( Runnable target): creates a new Thread object based on a Runnable object. Target refers to the object whose run method is called. Thread( Runnable target, String name): creates a new Thread object with the specified name and based on a Runnable object.
15 Ch-5: MultiThreading 03/01/2024
The Thread Class methods The Thread class has three primary methods that are used to control a thread: public void start(): prepares a thread to be run; public void run(): actually performs the work of the thread; public final void stop(): halts the thread; The thread dies when the run( ) method terminates or when the thread's stop( ) method is invoked. You never call run( ) explicitly. It is called automatically by the runtime as necessary once you've called start( ).
16 Ch-5: MultiThreading 03/01/2024
Thread methods public static Thread currentThread(): returns a reference to the thread that is currently running public final String getName(): returns the name of this thread. public final void setName(String name): renames the thread to the specified argument name, may throw Security Exception. public final int getPriority(): returns the priority assigned to this thread (setPriority(1-10))
17 Ch-5: MultiThreading 03/01/2024
… public final boolean isAlive(): indicates whether this thread is running or not. public void interrupt():interrupts this thread, causing it to continue execution if it was blocked for any reason. public final void join(long millisec): The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes
18 Ch-5: MultiThreading 03/01/2024
Static Methods Static methods performs the operation on the currently running thread. public static void yield():Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled. public static void sleep(long millisec):Causes the currently running thread to block for at least the specified number of milliseconds. public static boolean holdsLock(Object x):Returns true if the current thread holds the lock on the given Object. public static Thread currentThread():Returns a reference to the currently running thread, which is the thread that invokes this method. 19 Ch-5: MultiThreading 03/01/2024 Creating threads There are two ways to create a thread in a Java program. 1. Thread constructor or by instantiating classes that extend the Thread class or 2. Implementing Runnable interface When we talk about threads in Java programs, there are two related entities we may be referring to: the actual thread that is doing the work or the Thread object that represents the thread. The running thread is generally created by the operating system; the Thread object is created by the Java VM as a means of controlling the associated thread.
20 Ch-5: MultiThreading 03/01/2024
Extending Thread class The subclass extends Thread class The subclass overrides the run() method of Thread class An object instance of the subclass can then be created Calling the start() method of the object instance starts the execution of the thread Java runtime starts the execution of the thread by calling run() method of object instance Example
21 Ch-5: MultiThreading 03/01/2024
Implementing Runnable Interface The Runnable interface should be implemented by any class whose instances are intended to be executed as a thread The class must define run() method of no arguments The run() method is like main() for the new thread Provides the means for a class to be active while not subclassing Thread A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target 1. Example1
22 Ch-5: MultiThreading 03/01/2024
Starting Threads Creating threads and starting threads are not the same. A thread doesn't actually begin to execute until another thread calls the start() method on the Thread object for the new thread. The Thread object exists before its thread actually starts, and it continues to exist after its thread exits. It's generally a bad idea to start() threads from within a constructor. Doing so could expose partially constructed objects to the new thread. If an object owns a thread, then it should provide a start() or init() method that will start the thread, rather than starting it from the constructor.
23 Ch-5: MultiThreading 03/01/2024
Ending threads A thread will end in one of three ways: The thread comes to the end of its run() method. The thread throws an Exception or Error that is not caught. Another thread calls one of the deprecated stop() methods. Deprecated means they still exist, but you shouldn't use them in new code and should strive to eliminate them in existing code. When all the threads within a Java program complete, the program exits.
24 Ch-5: MultiThreading 03/01/2024
Exercise1 Program that creates three tasks and three threads to run them: The first task prints the letter a 100 times. The second task prints the letter b 100 times. The third task prints the integers 1 through 100. When you run this program, the three threads will share the CPU and take turns printing letters and numbers on the console. Source Code
25 Ch-5: MultiThreading 03/01/2024
Exercise 1 The main program creates a new thread, binds it to u, and starts it. Now two threads are executing concurrently: one executes main, and another executes run. While the main method is blocked waiting for keyboard input, the new thread keeps incrementing i. The new thread executes yield() to make sure that the other thread is allowed to run (when not blocked).
26 Ch-5: MultiThreading 03/01/2024
Joining with threads The Thread API contains a method for waiting for another thread to complete: the join() method. When you call Thread.join(), the calling thread will block until the target thread completes. Thread.join() is generally used by programs that use threads to partition large problems into smaller ones, giving each thread a piece of the problem.
27 Ch-5: MultiThreading 03/01/2024
Scheduling Except when using Thread.join() and Object.wait(), the timing of thread scheduling and execution is nondeterministic. If two threads are running at the same time and neither is waiting, you must assume that between any two instructions, other threads may be running and modifying program variables. If your thread will be accessing data that may be visible to other threads, such as data referenced directly or indirectly from static fields (global variables), you must use synchronization to ensure data consistency. There are two factors for scheduling a thread 28 i.e. Priority and Time of arrival. Ch-5: MultiThreading 03/01/2024 Example: public class TwoThreads { public static class Thread1 extends Thread { public void run() { System.out.println("A"); System.out.println("B"); } } public static class Thread2 extends Thread { public void run() { System.out.println("1"); System.out.println("2"); } } public static void main(String[] args) { new Thread1().start(); new Thread2().start(); } } 29 Ch-5: MultiThreading 03/01/2024 Example: explained We have no idea in what order the lines will execute, except that "1" will be printed before "2” and "A" before "B." The output could be any one of the following: 1 2 A B 1 A 2 B 1 A B 2 A 1 2 B A 1 B 2 A B 1 2 Not only may the results vary from machine to machine, but running the same program multiple times on the same machine may produce different results. Never assume one thread will do something before another thread does, unless you've used synchronization to force a specific ordering of execution. 30 Ch-5: MultiThreading 03/01/2024 Sleeping The Thread API includes a sleep() method, which will cause the current thread to go into a wait state until the specified amount of time has elapsed or until the thread is interrupted by another thread calling Thread.interrupt() on the current thread's Thread object. When the specified time elapses, the thread again becomes runnable and goes back onto the scheduler's queue of runnable threads. If a thread is interrupted by a call to Thread.interrupt(), the sleeping thread will throw an InterruptedException so that the thread will know that it was awakened by an interrupt and won't have to check to see if the timer expired. The Thread.yield() method is like Thread.sleep(), but instead of sleeping, it simply pauses the current thread momentarily so that other threads can run. In most implementations, threads with lower priority will not run when a thread of higher priority calls Thread.yield(). 31 Ch-5: MultiThreading 03/01/2024 Daemon threads We mentioned that a Java program exits when all of its threads have completed, but this is not exactly correct. What about the hidden system threads, such as the garbage collection thread and others created by the JVM? We have no way of stopping these. If those threads are running, how does any Java program ever exit? These system threads are called daemon threads. A Java program actually exits when all its non-daemon threads have completed. Any thread can become a daemon thread. You can indicate a thread is a daemon thread by calling the Thread.setDaemon() method. You might want to use daemon threads for background threads that you create in your programs, such as timer threads or other deferred event threads, which are only useful while there are other non-daemon threads running. 32 Ch-5: MultiThreading 03/01/2024 Using TimerTask The TimerTask allows you to execute a task at a later time (that is, for example, run a task once ten seconds from now), or to execute a task periodically (that is, run a task every ten seconds). Implementing the Timer class is quite straightforward: it creates a timer thread and builds a queue of waiting events sorted by execution time. The TimerTask thread is marked as a daemon thread so it doesn't prevent the program from exiting. Because timer events execute in the timer thread, you must make sure that access to any data items used from within a timer task is properly synchronized.
33 Ch-5: MultiThreading 03/01/2024
Example: In the CalculatePrimes example, instead of having the main thread sleep, we could have used a TimerTask as follows:
public static void main(String[] args) {
Timer timer = new Timer(); final CalculatePrimes calculator = new CalculatePrimes(); calculator.start(); timer.schedule(new TimerTask() { public void run() { calculator.finished = true; } }, TEN_SECONDS); }
34 Ch-5: MultiThreading 03/01/2024
Sharing access to data
35 Ch-5: MultiThreading 03/01/2024
Sharing variables For multiple threads to be useful in a program, they have to a way to communicate or share their results with each other. The simplest way for threads to share their results is to use shared variables. They should also use synchronization to ensure that values are propagated correctly from one thread to another and to prevent threads from seeing inconsistent intermediate results while another thread is updating several related data items. We Understanding the problem without Synchronization Example without Synchronization Example with Synchronization
36 Ch-5: MultiThreading 03/01/2024
Thread Synchronization When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this synchronization is achieved is called thread synchronization. The Java language provides two keywords for ensuring that data can be shared between threads in a controlled manner: synchronized and volatile. synchronized(object) { // statements to be synchronized }
37 Ch-5: MultiThreading 03/01/2024
… Synchronized has two important meanings: it ensures that only one thread executes a protected section of code at one time (mutual exclusion or mutex), and it ensures that data changed by one thread is visible to other threads (visibility of changes). Without synchronization, it is easy for data to be left in an inconsistent state. Synchronization allows us to define blocks of code that must run atomically, in which they appear to execute in an all-or- nothing manner, as far as other threads can tell.
38 Ch-5: MultiThreading 03/01/2024
… Volatile is simpler than synchronization and is suitable only for controlling access to single instances of primitive variables -- integers, booleans, and so on. When a variable is declared volatile, any write to that variable will go directly to main memory, bypassing the cache, while any read of that variable will come directly from main memory, by passing the cache. This means that all threads see the same value for a volatile variable at all times.
39 Ch-5: MultiThreading 03/01/2024
synchronization Using synchronized blocks allows you to perform a group of related updates as a set without worrying about other threads interrupting or seeing the intermediate results of a computation. The following example code will either print "1 0" or "0 1." In the absence of synchronization, it could also print "1 1" (or even "0 0," ).
public class SyncExample {
private static Object lockObject = new Object(); static int x,y; private static class Thread1 extends Thread { public void run() { synchronized (lockObject) { x = y = 0; System.out.println(x); } } } 40 Ch-5: MultiThreading 03/01/2024 Example: (cont’d) private static class Thread2 extends Thread { public void run() { synchronized (lockObject) { x = y = 1; System.out.println(y); } } } public static void main(String[] args) { new Thread1().start(); new Thread2().start(); } }
41 Ch-5: MultiThreading 03/01/2024
Java locking Java locking incorporates a form of mutual exclusion. Only one thread may hold a lock at one time. Locks are used to protect blocks of code or entire methods, but it is important to remember that it is the identity of the lock that protects a block of code, not the block itself. One lock may protect many blocks of code or methods. Conversely, just because a block of code is protected by a lock does not mean that two threads cannot execute that block at once. In the following example, the two threads are free to execute the synchronized block in setLastAccess() simultaneously because each thread has a different value for thingies. Therefore, the synchronized block is protected by different locks in the two executing threads. 42 Ch-5: MultiThreading 03/01/2024 Example: public class SyncExample { } } public static class Thingie { public static void main() { private Date lastAccess; Thingie thingie1 = new Thingie(), public synchronized void Thingie thingie2 = new Thingie(); setLastAccess(Date date) { new MyThread(thingie1).start(); this.lastAccess = date; new MyThread(thingie2).start(); } } } public static class MyThread extends } Thread { private Thingie thingie; public MyThread(Thingie thingie) { this.thingie = thingie; } public void run() {
thingie.setLastAccess(new Date());
43 Ch-5: MultiThreading 03/01/2024
Synchronized methods The simplest way to create a synchronized block is to declare a method as synchronized. This means that before entering the method body, the caller must acquire a lock: public class Point { public synchronized void setXY(int x, int y) { this.x = x; this.y = y; } } Just because setXY() is declared as synchronized doesn't mean that two different threads can't still execute setXY() at the same time, as long as they are invoking setXY() on different Point instances. Only one thread can execute setXY(), or any other synchronized method of Point, on a single Point instance at one time. 44 Ch-5: MultiThreading 03/01/2024 Synchronized blocks Its syntax is a little more complicated than for synchronized methods because you also need to explicitly specify what lock is being protected by the block. The following version of Point is equivalent to the version shown in the previous slide: public class Point { public void setXY(int x, int y) { synchronized (this) { this.x = x; this.y = y; } } } It is common, but not required, to use the this reference as the lock. This means that the block will use the same lock as synchronized methods in that class. Access to local (stack-based) variables never need to be protected, because they are only accessible from the owning thread.