Threads- tutorial updated for J2SE6.ppt

上传人:visitstep340 文档编号:373401 上传时间:2018-10-05 格式:PPT 页数:99 大小:576KB
下载 相关 举报
Threads- tutorial updated for J2SE6.ppt_第1页
第1页 / 共99页
Threads- tutorial updated for J2SE6.ppt_第2页
第2页 / 共99页
Threads- tutorial updated for J2SE6.ppt_第3页
第3页 / 共99页
Threads- tutorial updated for J2SE6.ppt_第4页
第4页 / 共99页
Threads- tutorial updated for J2SE6.ppt_第5页
第5页 / 共99页
亲,该文档总共99页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

1、Threads: tutorial updated for J2SE6,Threads and processes,A process has a self-contained execution environment. generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. Threadssometimes called lightweight processes. Threads exist within

2、 a process every process has at least one. Threads share the processs resources, including memory and open files.,Creating a thread with Runnable,Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is p

3、assed to the Thread constructor, as in the HelloRunnable example:,public class HelloRunnable implements Runnable public void run() System.out.println(“Hello from a thread!“); public static void main(String args) (new Thread(new HelloRunnable().start(); ,Creating a thread by subclassing Thread,Subcla

4、ss Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:,public class HelloThread extends Thread public void run() System.out.println(“Hello from a thread!“)

5、; public static void main(String args) (new HelloThread().start(); ,Sleep(),Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads or other applications. The sleep method can also be used

6、for pacing and waiting for another thread with duties that are understood to have time requirements. Two overloaded versions of sleep are provided: sleep time in millisecond and sleep time in nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the fac

7、ilities provided by the underlying OS. The sleep period can be terminated by interrupts. Need try/catch or throws.,public class SleepMessages public static void main(String args ) throws InterruptedException String importantInfo = “Mares eat oats“, “Does eat oats“, “Little lambs eat ivy“, “A kid wil

8、l eat ivy too“ ; for (int i = 0; i importantInfo.length; i+) /Pause for 4 seconds Thread.sleep(4000); /Print a message System.out.println(importantInfoi); ,print messages at four-second intervals,Interrupt,An interrupt is an indication to a thread that it should stop what it is doing and do somethin

9、g else. Its up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.,The code simply tests for the interrupt and exits the thread if one has been received. In more complex applications, it might make more sense to throw an Inter

10、ruptedException:,if (Thread.interrupted() throw new InterruptedException(); ,join,The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing, t.join(); causes the current thread to pause execution until ts thread terminates. O

11、verloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify. Like sleep, join responds to an interrupt by exiting with an InterruptedException.,example,S

12、impleThreads consists of two threads. The first is the main thread that every Java application has. The main thread creates a new thread from the Runnable object, MessageLoop, and waits for it to finish. If the MessageLoop thread takes too long to finish, the main thread interrupts it. See the accom

13、panying files now (SimpleThreads.java).,Thread communication,Threads communicate primarily by sharing access to fields and the objects reference fields refer to. two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronizatio

14、n.,Thread Interference,class Counter private int c = 0; public void increment() c+; public void decrement() c-; public int value() return c; ,Interference happens when two operations, running in different threads, but acting on the same data, interleave. This means that the two operations consist of

15、 multiple steps, and the sequences of steps overlap. Even simple statements can translate to multiple steps by the virtual machine. Simple, one liner is not always safe. single expression c+ can be decomposed into three steps: Retrieve the current value of c. Increment the retrieved value by 1. Stor

16、e the incremented value back in c.,Suppose Thread A invokes increment at about the same time Thread B invokes decrement. If the initial value of c is 0, their interleaved actions might follow this sequence: Thread A: Retrieve c. Thread B: Retrieve c. Thread A: Increment retrieved value; result is 1.

17、 Thread B: Decrement retrieved value; result is -1. Thread A: Store result in c; c is now 1. Thread B: Store result in c; c is now -1.,Thread As result is lost, overwritten by Thread B. This particular interleaving is only one possibility.,Memory Consistency Errors,occur when different threads have

18、inconsistent views of what should be the same data. The key to avoiding memory consistency errors is understanding the happens-before relationship. This relationship is simply a guarantee that memory writes by one specific statement are visible to another specific statement. To see this, consider th

19、e following example. Supppose a simple int field is defined and initialized:,int counter = 0; The counter field is shared between two threads, A and B. Suppose thread A increments counter: counter+; Then, shortly afterwords, thread B prints out counter: System.out.println(counter); If the two statem

20、ents had been executed in the same thread, it would be safe to assume that the value printed out would be “1“. But if the two statements are executed in separate threads, the value printed out might well be “0“, because theres no guarantee that thread As change to counter will be visible to thread B

21、 unless the programmer has established a happens-before relationship between these two statements.,There are several actions that create happens-before relationships. One of them is synchronization. Weve already seen two actions that create happens-before relationships. When a statement invokes Thre

22、ad.start, every statement that has a happens-before relationship with that statement also has a happens-before relationship with every statement executed by the new thread. The effects of the code that led up to the creation of the new thread are visible to the new thread. When a thread terminates a

23、nd causes a Thread.join in another thread to return, then all the statements executed by the terminated thread have a happens-before relationship with all the statements following the successful join. The effects of the code in the thread are now visible to the thread that performed the join.,Synchr

24、onized Methods,public class SynchronizedCounter private int c = 0; public synchronized void increment() c+; public synchronized void decrement() c-; public synchronized int value() return c; ,If count is an instance of SynchronizedCounter, then making these methods synchronized has two effects: Firs

25、t, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with t

26、he object. Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads. Note that constructors cann

27、ot be synchronized using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesnt make sense, because only the thread that creates an object should have access to it while it is being constructed.,Warning about sync,When constructing an object that will be sha

28、red between threads, be very careful that a reference to the object does not “leak“ prematurely. For example, suppose you want to maintain a List called instances containing every instance of class. You might be tempted to add the line instances.add(this); to your constructor. But then other threads

29、 can use instances to access the object before construction of the object is complete.,Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors. This strategy is effective, but can present problems with liveness.,Intrinsic Locks and Synchronizati

30、on,Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an objects fields has to acquire the objects intrinsic lock before accessing

31、 them, and then release the intrinsic lock when its done with them.,A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it a

32、ttempts to acquire the lock. When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquistion of the same lock.,Locks In Synchronized Methods,When a thread invokes a synchronized method, it automatically acquires the intrinsic l

33、ock for that methods object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.,What if we have a static synchronized method?,A static method is associated with a class, not an object. In this case, the thread acquires the intrinsi

34、c lock for the Class object associated with the class. Thus access to classs static fields is controlled by a lock thats distinct from the lock for any instance of the class.,Synchronized Statements,public void addName(String name) synchronized(this) lastName = name; nameCount+; nameList.add(name);

35、,In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects methods. (Invoking other objects methods from synchronized code can create Liveness problem.) Without synchronized statements, there would h

36、ave to be a separate, unsynchronized method for the sole purpose of invoking nameList.add.,Another Example,class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but theres no reason to prevent an update of c1 from being inte

37、rleaved with an update of c2 and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.,public class MsLunch private long c1 = 0; private long c2 = 0; privat

38、e Object lock1 = new Object(); private Object lock2 = new Object(); public void inc1() synchronized(lock1) c1+; public void inc2() synchronized(lock2) c2+; ,Reentrant Synchronization,A thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowin

39、g a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchro

40、nized code would have to take many additional precautions to avoid having a thread cause itself to block.,Atomic Access,In programming, an atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesnt happen at all.

41、No side effects of an atomic action are visible until the action is complete.,c+ does not describe an atomic action. Even very simple expressions can define complex actions that can decompose into other actions. However, there are actions you can specify that are atomic: Reads and writes are atomic

42、for reference variables and for most primitive variables (all types except long and double). Reads and writes are atomic for all variables declared volatile (including long and double variables).,Atomic actions cannot be interleaved, so they can be used without fear of thread interference. However,

43、this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible. Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of th

44、at same variable. This means that changes to a volatile variable are always visible to other threads. Whats more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.,Using simple

45、 atomic variable access is more efficient than accessing these variables through synchronized code, but requires more care by the programmer to avoid memory consistency errors. Whether the extra effort is worthwhile depends on the size and complexity of the application.,Liveness,A concurrent applica

46、tions ability to execute in a timely manner is known as its liveness. 3 kinds, deadlock starvation livelock.,Deadlock,Two or more threads are blocked forever, waiting for each other. Example: A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a ch

47、ance to return the bow. Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time.,See Deadlock.java,public synchronized void bow(Friend bower) /print somethingbower.bowBack(this); public synchronized void bowBack(Friend bower) /print oth

48、er things ,Bow, sync on A,Wait for Bs bowback, but is stuck because B owns the lock of B. So thread A cannot own it. (same for B- waiting for A),Starvation,Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happen

49、s when shared resources are made unavailable for long periods by “greedy“ threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same

50、 object will often be blocked.,Livelock,A thread often acts in response to the action of another thread. If the other threads action is also a response to the action of another thread, then livelock may result. As with deadlock, livelocked threads are unable to make further progress. However, the th

51、reads are not blocked they are simply too busy responding to each other to resume work. This is comparable to two people attempting to pass each other in a corridor: Alphonse moves to his left to let Gaston pass, while Gaston moves to his right to let Alphonse pass. Seeing that they are still blocking each other, Alphone moves to his right, while Gaston moves to his left. Theyre still blocking each other, so.,

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 教学课件 > 大学教育

copyright@ 2008-2019 麦多课文库(www.mydoc123.com)网站版权所有
备案/许可证编号:苏ICP备17064731号-1