* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Multithreading
Survey
Document related concepts
Java syntax wikipedia , lookup
Join-pattern wikipedia , lookup
Resource management (computing) wikipedia , lookup
Design Patterns wikipedia , lookup
Parallel computing wikipedia , lookup
Class (computer programming) wikipedia , lookup
Java (programming language) wikipedia , lookup
Java performance wikipedia , lookup
Name mangling wikipedia , lookup
Scheduling (computing) wikipedia , lookup
Object-oriented programming wikipedia , lookup
C Sharp syntax wikipedia , lookup
C Sharp (programming language) wikipedia , lookup
Transcript
Multithreading Definition: A thread is a single sequential flow of control within a program. (Sun’s definition) A thread--sometimes called an execution context or a lightweight process--is a single sequential flow of control within a program. You use threads to isolate tasks. Threads vs. processes Processes have their own resources such as memory. They are isolated by O/S such that one process cannot overwrite memory that belongs to another process. In a machine with a single processor, the O/S switches back and forth between multiple processes (known as time slicing), giving the illusion that they are running in parallel. But the switching is expensive as compared to using multiple threads that all share the resources assign to the same host process. Why use threads? - separate I/O activities and processor-heavy tasks (such as number-crunching) - process requests from multiple clients concurrently - modeling multiple objects that perform activities concurrently (such as flowing traffic) Ways to create and run threads in Java Basic support for threads in all versions of the Java platform is in the java.lang.Thread class. It provides a thread API and all the generic behavior for threads. These behaviors include starting, sleeping, running, yielding, and having a priority. To implement a thread using the Thread class, you need to provide it with a run method that performs the thread’s task. public class SimpleThread extends Thread { //subclassing public SimpleThread(String str) { super(str); //named thread } public void run() { //provide a run ... ... //method } } public class TwoThreadsDemo { public static void main (String[] args) { new SimpleThread("Jamaica").start(); //start a new SimpleThread("Fiji").start(); //thread } } Since multiple-inheritance is not supported in Java, an alternative way is provided for creating a class of objects that needs to inheritance from a class other than Thread yet still needs to be executed in a separate thread. The class can implement the Runnable interface, like the Thread class itself does. The same trick will be used as is with using the Thread class directly is to provide the run method, the only method defined in the Runnable interface. The slight different is in the way to create a thread for this Runnable type as demonstrated in the example given below. public class Clock extends Applet implements Runnable { private Thread clockThread = null; public void start() { if (clockThread == null) { clockThread = new Thread(this, "Clock"); clockThread.start(); } } public void run() { ... ... } Life cycle of a thread A thread may be in one of the following states: active Upon creation, a thread enters the new state, and it becomes after the start method is invoked. A runnable thread may be blocked (and thus becomes not runnable) for one three reasons: 1) blocked by an I/O resource; 2) chooses to delay a (finite or infinite) period of time (by invoking the sleep method); and 3) choose to wait until certain conditions become true (by invoking the wait method). Such a thread may then transit to the runnable state when 1) the I/O resource becomes available; 2) the period expires or got interrupted; or 3) got notified (by invoking the notify method), respectively. How to stop a thread A program doesn't stop a thread like it stops an applet (by calling a method). Rather, a thread arranges for its own death by having a run method that terminates naturally. (The stop and suspend methods in the Thread API are deprecated because they are inherently unsafe.) Active threads Being active simply means that a thread has been started and has not yet been stopped. An active object can be modeled with an object symbol with a bolder outline. Thread synchronization A program has at least one thread. Using multiple threads that won’t share any common resources usually won’t cause any problem, such as the programming exercise in workshop 4. When threads share access to a common object, they can conflict with each other. Consider several threads trying to access the same bank account, some trying to deposit and other to withdraw: these activities need to be synchronized. Java objects were designed with multithreading in mind: for every object there is a lock associated with it. The object can only be accessed by a thread that possesses the lock at any given time. To prevent competing threads from accidentally corrupt the state of the shared object, use one of the following two common synchronization mechanisms: a) Synchronized method. In the definition of a class for objects that require mutual exclusive access, define critical methods using the synchronized keyword in their headings. A thread that holds the object lock may choose to wait until a certain condition becomes true. The operation that may trigger the condition change should invoke the notifyAll method to wake up all threads that are waiting on the lock (or the notify method for just one waiting thread.) public class Queue { public synchronized void add(Object obj) throws InterruptedException { while (isFull()) wait(); //choose to block ... ... //until space available } public synchronized Object dequeue() { ... ... Object r = elements[head]; ... notifyAll(); //unblock all waiting threads return r; } ... ... } b) Synchronized block. Instead of specifying the whole method as synchronized, it is also possible to use a synchronized block, such as synchronized (anObject) { ... ... } References Java Online Tutorials. Essential Java classes/Lesson: Thread http://java.sun.com/docs/books/tutorial/essential/threads/index.html Wigglesworth and McMillan, Java Programming: Advanced Topics, 3rd edition, Course Technology 2004 Horstmann, Object-Oriented Design and Patterns, Wiley 2004