Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Lecture 16 Introduction to Multithreading and Concurrency Overview  Introduction to Multithreading of Computation  Where are Threads used?  Why should.

Similar presentations


Presentation on theme: "1 Lecture 16 Introduction to Multithreading and Concurrency Overview  Introduction to Multithreading of Computation  Where are Threads used?  Why should."— Presentation transcript:

1 1 Lecture 16 Introduction to Multithreading and Concurrency Overview  Introduction to Multithreading of Computation  Where are Threads used?  Why should you use threads ?  Multithreading: Common Terminology.  Thread States: Lifetime of a Thread.  Some Examples.  Preview: Threads and Concurrency (continued).

2 2 Lecture 16 What is a Thread? A thread is a single sequential execution path in a program. Every program has at least one thread. Each thread has its own stack, priority, and virtual set of registers. Threads subdivide the run-time behavior of a program into separate, independently running subtasks Just like human being can walk, talk, see, hear etc at the same time, computers can also download documents, print a file, receive e-mail concurrently.  Computers normally achieve concurrency using threads. A thread or thread of control is a section of code executed independently of other threads of control within a single program Computers normally achieve concurrency using threads. A thread or thread of control is a section of code executed independently of other threads of control within a single program While most programming languages (like C, C++) do not provide concurrency, Java does and is unique in this aspect. Multiple threads on multiple CPUs Multiple threads sharing a single CPU

3 3 Lecture 16 Where Are Threads Used? Threads are used by virtually every computer user in the following instances: –In many applications (such as printing) –In programs such as Internet browsers –In databases –In the operating systems Threads are often used without your knowledge More productivity to the end user (such as responsive user interface) More efficient use of the computer (such as using the CPU while performing input-output) Sometimes advantageous to the programmer (such as simplifying program logic) Why Should You Use Threads?

4 4 Lecture 16 Introduction to Threads of Computation (cont.)  A program launches a thread’s execution by calling the thread’s start() method, which, in turn, calls the run() method.  The code that “does the real work” of a thread is placed in the run() method. Thus, run( ) is the code that will be executed “simultaneously” with the other threads in a program.  After start() launches the thread, start() returns to its caller immediately. The caller then executes concurrently with the thread created. It is an error to call start() twice for the same thread.  Every Java thread has a priority in the range Thread.MIN_PRIORITY (a constant 1) and Thread.MAX_PRIORITY (a constant of 10). By default, each thread is given priority Thread.NORMAL_PRIORITY (a constant of 5).  Each new thread inherits the priority of the thread that creates it.  Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.  Every Java applet or application is multithreaded.

5 5 Lecture 16 Multithreading: Common Terminology  Thread scheduling: arranging the threads to be executed in an order that they may take CPU control.  Timeslice: The length of time for which a thread runs and this time may depend on the thread's priority or its use of resources such as memory and I/O  Preemption: to interrupt and suspend (“swap out”) the currently executing thread in order to start or continue running ("swap in") another thread.  Synchronization: The process of ensuring that that a shared resource is used by only one of the many contending threads at any moment.  Deadlock: A situation where two or more threads are unable to proceed because each is waiting for one of the others to do something  Starvation: indefinite postponement of the execution of lower-priority threads by higher-priority ones.

6 6 Lecture 16 Thread States: Lifetime of a Thread.  The Thread class has two constructors: Thread(String threadName) and Thread() which creates automatically numbered threads.  Thread-related methods are: run(), start(), sleep(), interrupt(), yield(), isInterrupted(), isAlive(), getName(), etc  Born state  Thread just created  When start() called, enters ready state  Ready state (runnable state)  Highest-priority ready thread enters running state  Running state  System assigns processor to thread (thread begins executing)  When run() method completes or terminates, enters dead state  Dead state  Thread marked to be removed by system  Entered when run() terminates or throws uncaught exception

7 7 Lecture 16 Thread States: Lifetime of a Thread.  Blocked state  Entered from running state  Blocked thread cannot use processor, even if available  Common reason for blocked state - waiting on I/O request  Sleeping state  Entered when sleep() method called  Cannot use processor  Enters ready state after sleep time expires  Waiting state  Entered when wait() called in an object thread is accessing  One waiting thread becomes ready when object calls notify()  notifyAll() - all waiting threads become ready

8 8 Lecture 16 Thread Life Cycle New threadBlockedReady to Run Running Dead suspend() wait() sleep() other run() exits stop() Scheduled by JVM (calls run() ) Scheduled by JVM (calls run() ) start() resume() notifyAll() sleep finishes

9 9 Lecture 16 Creating a New Thread 1. Create the new class. a.Define a subclass of Thread. b.Override its run() method. 2. Instantiate and run the thread. a.Create an instance of the class. b.Call its start() method, which puts the thread in the queue. 3. The scheduler calls the thread ’ s run() method.

10 10 Lecture 16 Creating Threads by Implementing the Runnable Interface

11 11 Lecture 16 Example1 Using the Thread Class to Create and Launch Threads F Objective: Create and run three threads: –The first thread prints the letter a 100 times. –The second thread prints the letter b 100 times. –The third thread prints the integers 1 through 100. bbbbbbbbbbbbbbbbbbbbbbb 1b 2b 3b 4ba 5ba 6ba 7ba 8ba 9ba 10ba 11ba 12ba 13ba 1 a 15ba 16ba 17ba 18ba 19ba 20ba 21ba 22ba 23ba 24ba 25ba 26ba 27ba 28ba 29ba 3 a 31ba 32ba 33ba 34ba 35ba 36ba 37ba 38ba 39ba 40ba 41ba 42ba 43ba 44ba 45ba 4 a 47ba 48ba 49ba 50ba 51ba 52ba 53ba 54ba 55ba 56ba 57ba 58ba 59ba 60ba 61ba 6 a 63ba 64ba 65ba 66ba 67ba 68ba 69ba 70ba 71ba 72ba 73ba 74ba 75ba 76ba 77a 78 79a 80a 81a 82a 83a 84a 85a 86a 87a 88a 89a 90a 91a 92a 93a 94a 95a 96a 97a 98 99a 100aaa

12 12 Lecture 16 Example1 Using the Thread Class to Create and Launch Threads // TestThread.java: Define threads using the Thread class class TestThread { // Main method public static void main(String[] args) { // Create threads PrintChar printA = new PrintChar('a',100); PrintChar printB = new PrintChar('b',100); PrintNum print100 = new PrintNum(100); // Start threads print100.start(); printA.start(); printB.start(); } } / in specified times class PrintChar extends Thread { private char charToPrint;// The character to print private int times;//The times to repeat // Construct a thread with specified character and number of // times to print the character public PrintChar(char c, int t) { charToPrint = c; times = t; } /*override the run() method to tell the system what the thread will do*/ public void run() { for (int i=1;i<times; i++) System.out.print(charToPrint); } //The thread class for printing number from 1 to n for a given n class PrintNum extends Thread { private int lastNum; public PrintNum(int i) { lastNum=i; } public void run() { for (int i=1;i<=lastNum;i++) System.out.print(" "+i); }

13 13 Lecture 16 Creating New Threads  A new thread can be created by subclassing the Thread class and overriding its run() method or by implementing the Runnable interface.  Thread creation by subclassing Thread: class MyNewThread1 extends Thread { … public void run() {}//supply meaningful body here! } MyNewThread1 p = new MyNewThread1(); p.start();  Thread creation by implementing Runnable: class MyNewThread2 implements Runnable { … public void run(){}//supply meaningful body here! } Runnable p = new MyNewThread2 (); Thread th = new Thread(p); th.start();

14 14 Lecture 16 Example 1: Thread Creation using Thread Class class OurClass{ public void run(){ for(int i=0; i<100; i++) System.out.print("Salam "); } public class OurClassTester{ public static void main(String args[]){ OurClass oc = new OurClass(); oc.run(); run(); } static void run(){ for(int i=0; i<100; i++) System.out.print("Shabab."); }} class OurClass extends Thread{ public void run(){ for(int i=0; i<100; i++) System.out.print("Salam "); } public class OurClassTester2{ public static void main(String args[]){ OurClass oc = new OurClass(); oc.start(); run(); } static void run(){ for(int i=0; i<100; i++) System.out.print("Shabab."); }}

15 15 Lecture 16 Example 1: Thread Creation using Thread (cont.)  OurClassTester1 is a single-threaded running in the main() thread:  Creates an object, calls its run method, prints "Salam. " 100 times and then calls run() of OurClassTester1 to print "Shabab" 100 times.  What if we want the run() method of OurClass to execute concurrently with the main() method?  We need to modify OurClass to extend the Thread class (java.lang.Thread) as in OurClassTester2.  OurClassTester2 has a different behavior than OurclassTester1 because the former has two threads.  Run the programs and compare their results. Does the output of OurClassTester2 change from execution to execution?  Is there any change in the program output if you chage oc.start() to oc.run() in OurClassTester2 program? Why or why not?

16 16 Lecture 16 Example 2: Threads Creation with Runnable  In the preceding slides we have considered an example of threads creation by subclassing the Thread class.  We are now ready to take another example to illustrate the second method of threads creation; by implementing the Runnable interface.  First we note that this second methods we are about to see may be necessary in cases where our class has already inherited from another and can thus not inherit from the Thread class.  Note that if we implement the Runnable interface, then our class is not a Thread so we cannot call its run() method and expect the behaviour of a thread. We need to create a real Thread object and pass to it reference of our Runnable object using the constructor Thread(Runnable target).  The Runnable interface (java.lang.Runnable) contains only the run() method: public void run(){ if (target != null) target.run(); }  target is the Runnable object passed to the Thread constructor which is used in the Thread’s run() method to eventually call the run() method of OurClass.

17 17 Lecture 16 Example 2: Threads Creation with Runnable (cont.) class OurClass implements Runnable{ public void run(){ for(int i=0; i<100; i++) System.out.print("Salam "); } public class ImplementingRunnable{ public static void main(String args[]){ OurClass oc = new OurClass(); Thread th = new Thread(oc); th.start(); run(); } static void run(){ for(int i=0; i<100; i++) System.out.print("Shabab."); }  We know that implementing Runnable allows classes that already have fixed inheritance structures to be threaded without creating a new class.  Does threading by the Runnable interface solve a problem that cannot be solved by inheritance or vice-versa? No.  A similarity is that you must have a run() method to be executed, once the thread has been instantiated and started.  We believe choice should be dictated by clarity of solution.


Download ppt "1 Lecture 16 Introduction to Multithreading and Concurrency Overview  Introduction to Multithreading of Computation  Where are Threads used?  Why should."

Similar presentations


Ads by Google