Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.

Similar presentations


Presentation on theme: "1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread."— Presentation transcript:

1 1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread States: Lifetime of a Thread.  Common Terminology of threads.  Some more Examples.  Preview: Threads and Concurrency (continued).

2 2 Threads (Part I) Introduction to Threads of Computation (Cont’d)  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.  An example of concurrency is able to work in a word processor while downloading something from the internet.  While most programming languages (like C, C++) do not provide concurrency, Java does and is unique in this aspect.  Threads are Java’s way of making a single JVM look like many JVM.  This effect is usually an illusion. There is only one JVM and most often only one CPU, but the CPU switches among the JVM’s various threads to give the impression of multipleCPU’s.  Writing multithreaded programs is tricky: imagine reading three books by reading few words from each book for a few seconds repeatedly in succession  Although Java is portable, its multithreading is platform dependent: a multithreaded program could behave differently on different platforms:  Under Solaris implementation, an executing thread can run to completion or can be preempted by a higher priority thread.  On windows (NT and 98) threads are timesliced and preemption occurs with higher as well as with equal priority threads.

3 3 Threads (Part I) 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++) { sleep(100); 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."); }}

4 4 Threads (Part I) Example 1: Thread Creation using Thread (Cont’d)  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?

5 5 Threads (Part I) What does a Thread Executes  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.

6 6 Threads (Part I) Various States of a Thread Monitor States Sleeping Blocked Ready Running Suspended Yield() Sheduled Wait state

7 7 Threads (Part I) Various States of a Thread (Cont’d) l Ready: When you call start() on a thread, thread does not run immediately it goes into a ready-to run state and stays there until the scheduler moves it to the run state. l Running: This is the state which all threads aspire to enter. When the thread moves from ready state to running state, here the actual run() method is executed by the CPU. In the course of executing run(), the thread may temporarily give up he CPU and enter some other state for a while as shown in the figure. l Suspended: Suspending a thread is a mechanism that allows any arbitrary thread to make another thread unready for an indefinite period of time. The suspended thread becomes ready when some other thread resumes it. The corresponding methods are suspend() and resume(). These two methods are deprecated as of Java 2 release. l Sleeping: A sleeping thread passes time without doing anything and without using the CPU. A call to the sleep() method requests the currently executing thread to cease executing for a specified amount of time. public static void sleep(long milliseconds) throws InterruptedException This is a static method in the Thread class

8 8 Threads (Part I) Various States of a Thread (Cont’d) l Blocking: A method that performs input or output have to wait for some occurrences form the outside world before they can proceed. This state is called blocking. l Yielding: A thread by itself can offer to move out of the virtual CPU by yielding. A call to the yield() method causes the currently executing thread to move to the ready state. l Dead: When the run method of a thread completes it enters the dead state, that is it finishes executing.  Waiting state: wait() tells the calling thread to go to sleep until some other thread calls notify() or notifyAll(). notify() notifies the first thread entered waiting state where as notifyAll() notifies all the thread in the waiting state.

9 9 Threads (Part I) 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.

10 10 Threads (Part I) 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();

11 11 Threads (Part I) 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.

12 12 Threads (Part I) Example 2: Threads Creation with Runnable (Cont’d) 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 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread."

Similar presentations


Ads by Google