Threads- tutorial updated for J2SE6.ppt
《Threads- tutorial updated for J2SE6.ppt》由会员分享,可在线阅读,更多相关《Threads- tutorial updated for J2SE6.ppt(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
- 1.请仔细阅读文档,确保文档完整性,对于不预览、不比对内容而直接下载带来的问题本站不予受理。
- 2.下载的文档,不会出现我们的网址水印。
- 3、该文档所得收入(下载+内容+预览)归上传者、原创作者;如果您是本文档原作者,请点此认领!既往收益都归您。
下载文档到电脑,查找使用更方便
2000 积分 0人已下载
下载 | 加入VIP,交流精品资源 |
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- THREADSTUTORIALUPDATEDFORJ2SE6PPT
