Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Threads Representation and Management of Data on the Internet.

Similar presentations


Presentation on theme: "Java Threads Representation and Management of Data on the Internet."— Presentation transcript:

1 Java Threads Representation and Management of Data on the Internet

2 Introduction It would be nice if we could focus our attention on performing only one action at a time and performing it well, but that’s usually difficult to do. The human body performs a great variety of operations in parallel—or, as we’ll say throughout this chapter, concurrently. Respiration, blood circulation, digestion, thinking and walking, for example, can occur concurrently, as can all the senses—sight, touch, smell, taste and hearing.

3 Computers, too, can perform operations concurrently. It’s common for personal computers to compile a program, send a file to a printer and receive electronic mail messages over a network concurrently. Only computers that have multiple processors can truly execute multiple instructions concurrently. single-processor Operating systems on single-processor computers create the illusion of concurrent execution by rapidly switching between activities, but on such computers only a single instruction can execute at once. multiple processors Today’s multicore computers have multiple processors that enable computers to perform tasks truly concurrently..

4 Java Concurrency Java makes concurrency available to you through the language and APIs. Java programs can have multiple threads of execution, where each thread has its own method-call stack and program counter, allowing it to execute concurrently with other threads while sharing with them application- wide resources such as memory. This capability is called multithreading.

5 Concurrent Programming Uses We’ll discuss many applications of concurrent programming. For example, when downloading a large file (e.g., an image, an audio clip or a video clip) over the Internet, the user may not want to wait until the entire clip downloads before starting the playback. To solve this problem, multiple threads can be used—one to download the clip, and another to play it. These activities proceed concurrently. To avoid choppy playback, the threads are synchronized (that is, their actions are coordinated) so that the player thread doesn’t begin until there’s a sufficient amount of the clip in memory to keep the player thread busy. The Java Virtual Machine (JVM) creates threads to run programs and threads to perform housekeeping tasks such as garbage collection.

6 Thread States: Life Cycle of a Thread At any time, a thread is said to be in one of several thread states—illustrated in following the UML state diagram

7 New and Runnable States A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread, which places it in the runnable state. A thread in the runnable state is considered to be executing its task. Waiting State Sometimes a runnable thread transitions to the waiting state while it waits for another thread to perform a task. A waiting thread transitions back to the runnable state only when another thread notifies it to continue executing. Timed Waiting State A runnable thread can enter the timed waiting state for a specified interval of time. It transitions back to the runnable state when that time interval expires or when the event it’s waiting for occurs. Timed waiting and waiting threads cannot use a processor, even if one is available..

8 Blocked State A runnable thread transitions to the blocked state when it attempts to perform a task that cannot be completed immediately and it must temporarily wait until that task completes. For example, when a thread issues an input/output request, the operating system blocks the thread from executing until that I/O request completes—at that point, the blocked thread transitions to the runnable state, so it can resume execution. A blocked thread cannot use a processor, even if one is available. Terminated State A runnable thread enters the terminated state (sometimes called the dead state) when it successfully completes its task or otherwise terminates (perhaps due to an error). In the UML state diagram of Fig. 26.1, the terminated state is followed by the UML final state (the bull’s-eye symbol) to indicate the end of the state transitions.a

9 Thread Priorities and Thread Scheduling Every Java thread has a thread priority that helps determine the order in which threads are scheduled. Each new thread inherits the priority of the thread that created it. Higher-priority threads are more important to a program and should be allocated processor time before lower-priority threads.

10 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 A thread is a single sequence of execution within a program Multithreading refers to multiple threads of control within a single program –each program can run multiple threads of control within it, e.g., Web Browser

11 Concurrency vs. Parallelism CPUCPU1CPU2

12 What are Threads Good For? To maintain responsiveness of an application during a long running task. To enable cancellation of separable tasks. Some problems are intrinsically parallel. To monitor status of some resource (DB). Some APIs and systems demand it.

13 Application Thread When we execute an application: –The JVM creates a Thread object whose task is defined by the main() method –It starts the thread –The thread executes the statements of the program one by one until the method returns and the thread dies

14 Multiple Threads in an Application Each thread has its private run-time stack If two threads execute the same method, each will have its own copy of the local variables the methods use.

15 Creating Threads There are two ways to create our own Thread object 1.Subclassing the Thread class and instantiating a new object of that class 2.Implementing the Runnable interface In both cases the run() method should be implemented

16 Creating and Starting Threads Creating a thread in Java is done like this: To start the thread you will call its start() method, like this:

17 There are two ways to specify what code the thread should execute. firstThe first is to create a subclass of Thread and override the run() method. secondThe second method is to pass an object that implements Runnable to the Thread constructor.

18 First way: Thread Subclass, is to create a subclass of Thread and override the run() method.The first way to specify what code a thread is to run, is to create a subclass of Thread and override the run() method. The run() method is what is executed by the thread after you call start(). Here is an example: To create and start the above thread you can do like this: hen the run() method executes it will print out the text "MyThread running".

19 Another example: Extending Thread public class ThreadExample extends Thread { public void run () { for (int i = 1; i <= 100; i++) { System.out.println(“Thread: ” + i); } To create and start the above thread ThreadExample thread1= new ThreadExample; Thread1.strat();

20 Second way: Runnable Interface Implemention The second way to specify what code a thread should run is by creating a class that implements java.lang.Runnable. The Runnable object can be executed by a Thread. To have the run() method executed by a thread, pass an instance of MyRunnable to a Thread in its constructor. Here is how that is done: MyRunnable runthread= new MyRunnable(); Thread thread1= newThread(runthread);

21 Another Example: Implementing Runnable public class RunnableExample implements Runnable { public void run () { for (int i = 1; i <= 100; i++) { System.out.println (“Runnable: ” + i); } } } To have the run() method executed by a thread RunableExample myrunable= new RunableExample(); Thread thread1= new Thread (myrunable); thread1.start();

22 Common Pitfall: Calling run() instead of start() When creating and starting a thread a common mistake is to call the run() method of the Thread instead of start(), like this:

23 Thread Methods void start() –Creates a new thread and makes it runnable –This method can be called only once void run() –The new thread begins its life inside this method void stop() (deprecated) –The thread is being terminated

24 Thread Methods yield() –Causes the currently executing thread object to temporarily pause and allow other threads to execute –Allow only threads of the same priority to run sleep(int m)/sleep(int m,int n) –The thread sleeps for m milliseconds, plus n nanoseconds

25 Scheduling Thread scheduling is the mechanism used to determine how runnable threads are allocated CPU time A thread-scheduling mechanism is either preemptive or nonpreemptive

26 Preemptive Scheduling Preemptive scheduling – the thread scheduler preempts (pauses) a running thread to allow different threads to execute Nonpreemptive scheduling – the scheduler never interrupts a running thread The nonpreemptive scheduler relies on the running thread to yield control of the CPU so that other threads may execute

27 Starvation A nonpreemptive scheduler may cause starvation (runnable threads, ready to be executed, wait to be executed in the CPU a lot of time, maybe even forever) Sometimes, starvation is also called a livelock

28 Time-Sliced Scheduling Time-sliced scheduling – the scheduler allocates a period of time that each thread can use the CPU –when that amount of time has elapsed, the scheduler preempts the thread and switches to a different thread Nontime-sliced scheduler – the scheduler does not use elapsed time to determine when to preempt a thread – it uses other criteria such as priority or I/O status

29 Java Scheduling Scheduler is preemptive and based on priority of threads Uses fixed-priority scheduling: –Threads are scheduled according to their priority w.r.t. other threads in the ready queue

30 Java Scheduling The highest priority runnable thread is always selected for execution above lower priority threads When multiple threads have equally high priorities, only one of those threads is guaranteed to be executing Java threads are guaranteed to be preemptive-but not time sliced Q: Why can’t we guarantee time-sliced scheduling? What is the danger of such scheduler?

31 Thread Priority Every thread has a priority When a thread is created, it inherits the priority of the thread that created it The priority values range from 1 to 10, in increasing priority

32 Thread Priority (cont.) The priority can be adjusted subsequently using the setPriority() method The priority of a thread may be obtained using getPriority() Priority constants are defined: –MIN_PRIORITY=1 –MAX_PRIORITY=10 –NORM_PRIORITY=5

33 Some Notes Thread implementation in Java is actually based on operating system support Some Windows operating systems support only 7 priority levels, so different levels in Java may actually be mapped to the same operating system level What should we do about this?

34 Daemon Threads Daemon threads are “background” threads, that provide services to other threads, e.g., the garbage collection thread The Java VM will not exit if non-Daemon threads are executing The Java VM will exit if only Daemon threads are executing Daemon threads die when the Java VM exits


Download ppt "Java Threads Representation and Management of Data on the Internet."

Similar presentations


Ads by Google