ImageVerifierCode 换一换
格式:PPT , 页数:72 ,大小:302KB ,
资源ID:378486      下载积分:2000 积分
快捷下载
登录下载
邮箱/手机:
温馨提示:
快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。 如填写123,账号就是123,密码也是123。
特别说明:
请自助下载,系统不会自动发送文件的哦; 如果您已付费,想二次下载,请登录后访问:我的下载记录
支付方式: 支付宝扫码支付 微信扫码支付   
验证码:   换一换

加入VIP,免费下载
 

温馨提示:由于个人手机设置不同,如果发现不能下载,请复制以下地址【http://www.mydoc123.com/d-378486.html】到电脑端继续下载(重复下载不扣费)。

已注册用户请登录:
账号:
密码:
验证码:   换一换
  忘记密码?
三方登录: 微信登录  

下载须知

1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。
2: 试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。
3: 文件的所有权益归上传用户所有。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 本站仅提供交流平台,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

版权提示 | 免责声明

本文(AppletsEvent HandlingThreads and more in Java.ppt)为本站会员(proposalcash356)主动上传,麦多课文库仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知麦多课文库(发送邮件至master@mydoc123.com或直接QQ联系客服),我们立即给予删除!

AppletsEvent HandlingThreads and more in Java.ppt

1、Applets Event Handling Threads and more in Java,Sami Khuri Mathematics & Computer Science Department,Creating the “First” Applet,Create a Java source file: First.java Compile First.java. The Java compiler creates the Java bytecode file First.class in the same directory. Create an HTML file First.htm

2、l, for example, that includes First.class. Run the applet in a Java-enabled browser or a Java applet viewing program.,java.lang.Object | +-java.awt.Component | +-java.awt.Container | +-java.awt.Panel | +-java.applet.Applet AWT: Abstract Windowing Toolkit,Applets,Methods defined in the class Applet:

3、init(): Applet is being loaded by browser. Used for one-time initialization. start(): Browser entered page containing applet stop(): Browser leaves page containing applet destroy(): Applet is discarded by browser. paint() is used for drawing on applets. It is a method in the class Component.,Java-en

4、abled Browser,When a Java-enabled browser encounters an tag, it: reserves a display area of the specified width and height for the applet loads the bytecodes for the specified Applet subclass creates an instance of the subclass calls the instances init() and start() methods.,HyperText Markup Languag

5、e,An HTML documents contains tags that specify formatting instructions.An HTML tag is enclosed in angle brackets: example and The width and height (in pixels) of the area in which the applet is displayed is included in the html file.,Inheriting from above classes,Some methods in Component: add(), re

6、move() and setLayout(): controls the positions & sizes of components. Applets inherit the drawing and event handling methods from AWT Component class to produce user interfaces. Drawing: images, control of color and font. UI components: buttons, etc Event handling: detecting & responding to mouse dr

7、agging, button pushing, key pressing,Component, Container, and Panel,From AWT Container, applets get methods to hold components & use layout managers. Panels and applets can only be displayed on other graphical surfaces. A panel must be added to another container in order to be displayed. A componen

8、t is added to a container by using add() from the Container class.,Security Restrictions,Restrictions imposed on applets loaded over the network. The applet cannot: Dynamically load native code libraries. Read from or write to the local file system. Make network connections to any computer except to

9、 the one from which it obtained the code. Read certain system properties. Start a printing job.,More Applet Capabilities,Applets can make network connections to the host from which they came. Applets that are loaded from the local file system (from a directory in the users CLASSPATH) have none of th

10、e restrictions that applets loaded over the network do. Applets can load data files (show images) and play sounds.,Displaying Images,The code base, returned by the Applet getCodeBase() method, is a URL that specifies the directory from which the applets classes were loaded. The document base, return

11、ed by the Applet getDocumentBase() method, specifies the directory of the HTML page that contains the applet.,Example on Displaying Images,Images must be in GIF or JPEG format. Example: Image file yawn.gif is in directory “images”. To create an image object “nekopicture” that contains “yawn.gif”: Im

12、age nekopicture = new Image nekopicture = getImage(getCodeBase(), “images/yawn.gif“);,Playing Sounds,The AudioClip interface in the Applet class provides basic support for playing sounds. Sound format: 8 bit, 8000 Hz, one-channel, Sun “.au“ files. Methods in AudioClip that need to be implemented in

13、the applet: loop(): starts playing the clip repeatedly play() & stop() to play & stop the clip.,Inheritance tree of applets & frames,Object,Component,Container,Window,Frame,Panel,Applet,Label,Canvas,Scrollbar,Choice,List,Button,Checkbox,TextComponent,Event Handling,With event-driven programming, eve

14、nts are detected by a program and handled appropriately Events: moving the mouse clicking the button pressing a key sliding the scrollbar thumb choosing an item from a menu,Three Steps of Event Handling,Prepare to accept events import package java.awt.event Start listening for events include appropr

15、iate methods Respond to events implement appropriate abstract method,1. Prepare to accept events,Import package java.awt.event Applet manifests its desire to accept events by promising to “implement” certain methods Example: “ActionListener” for Button events “AdjustmentListener” for Scrollbar event

16、s,2. Start listening for events,To make the applet “listen” to a particular event, include the appropriate “addxxxListener”. Examples: addActionListener(this) shows that the applet is interested in listening to events generated by the pushing of a certain button.,2. Start listening for events (cont)

17、,Example addAdjustmentListener(this) shows that the applet is interested in listening to events generated by the sliding of a certain scroll bar thumb. “this” refers to the applet itself - “me” in English,3. Respond to events,The appropriate abstract methods are implemented. Example: actionPerformed

18、() is automatically called whenever the user clicks the button. Thus, implement actionPerformed() to respond to the button event.,3. Respond to events (cont),Example: adjustmentValueChanged() is automatically invoked whenever the user slides the scroll bar thumb. So adjustmentValueChanged() needs to

19、 be implemented. In actionPerformed(ActionEvent evt), ActionEvent is a class in java.awt.event.,north,center,south,leftMsg,rightMsg,centerValue,ranger,statement,pan2,pan3,pan1,StatBar,Threads,A lightweight sequential flow of control that shares an address space and resources with other threads. A th

20、read, unlike processes (heavyweight), has a low context switching time. Threads are indispensable for sockets, image holding, and animation.,Threads in Java,Traditionally, threads are implemented at the system level, separate from the programming language. Java is a language and a runtime system and

21、 threads are integrated in both. The keyword synchronize is used to make a block of code accessible to at most one thread at a time.,Purpose of Threads,Making a User Interface more responsive. When one method can use the partial output of another without waiting for the first one to finish. Example:

22、 image-loading and image-displaying methods. Any type of application that lends itself to concurrency.,How to create threads,There are two ways of creating threads in Java: 1) Extend the “Thread” classWe can instantiate the class Thread as many times as desired to achieve multi-threading. 2) Impleme

23、nt the “Runnable” interfaceSince multiple inheritance is not allowed in Java, this method is used when the program already extends another class (Ex. Applets),1) Extend the Thread class,Create a subclass of java.lang.Thread: public class MyThread extends Thread public void run() put code here Instan

24、tiate MyThread: MyThread myTrd; myTrd.start(); / calls run() in MyThread,Methods in Class Thread,Three primary methods to control a thread: public native synchronized void start()prepares a thread to run public void run()actually performs the work of the thread public final void stop()to terminate t

25、he thread. The thread also dies when run() terminates.,start() & run() in Thread,start() causes the thread to begin execution and the Java Virtual Machine calls run(). Thus, we never have to call run() explicitly. The result is that two threads are running concurrently: the current thread which retu

26、rns from the call to start() and the thread that executes run().,Other Methods in Thread,Other important methods in Thread include: suspend() and resume() sleep(mls) which causes the thread to temporarily stop execution for mls milliseconds yield() which causes the executing thread object to tempora

27、rily pause and allow other threads to execute getName() and getPriority(),Class Thread Priorities,The class Thread has three fields: MAX_PRIORITY MIN_PRIORITY NORM_PRIORITY: the default priority assigned to a thread A new created thread has its priority initially set equal to the priority of the cre

28、ating thread.,2) Creating a thread by using Runnable Interface,Instantiate Thread and pass it “this” (the applet) as a parameter. Use the method start() to start running the instantiated thread. Place all the important code for the instantiated thread in the run() method. Set the instantiated thread

29、 to “null” in the stop() method.,Implement Runnable interface,Create a class that implements Runnable: public class MyFoo extends Applet implements Runnable; Runnable is an interface in java.lang that contains only one method: run(). Multiple inheritance is not allowed in Java, thus this method of c

30、reating threads is used when MyFoo already extends another class.,The Life Cycle of a Thread,New Thread,Not Runnable,Dead,Runnable,running,start(),run() terminates,In and Out of Runnable,Out of Runnable sleep() is invoked. wait() is invoked (for a specified condition to be satisfied). Thread is bloc

31、ked on I/O.,Back to Runnable Specified number of milliseconds elapsed. An object notifies the waiting thread that the condition is satisfied. I/O event the thread is blocked on, is completed.,new,dead,runnable,blocked,start,stop,sleep,Done sleeping,suspend,resume,wait,notify,Block on I/O,I/O complet

32、e,Thread States from Core Java. Drawn by Ping Wu,Managing Threads,Launching threads and letting them compete for computer resources, in an uncontrolled fashion, may lead to very unpleasant results. A typical application involves two or more threads that share a common resource: file or block of memo

33、ry, where one thread tries to modify the resource while that resource is still being used by another thread.,Simple Model of a Bank Horton97,A very small bank consists of: a bank: a computer that performs operations on accounts clerk1: processes credits (deposits) clerk2: processes debits (withdrawa

34、ls) Each clerk can communicate directly with the bank Initially, the bank has only one customer,theAccount,theBank,Credit operationsDebit operations,Credits,Debits,clerk1,clerk2,Computer operations are overlapped,Four Classes of the Bank Model,public class Account field: balance getBalance() and set

35、Balance(balance) class Bank where credit & debit operations are performed and balance is updated. public void credit(Account theAcc, int amt) public void debit(Account theAcc, int amt),Clerk Class,public class Clerk implements Runnable Bank theBank / The employer / Types of transactions / Details of

36、 the current transaction public void doCredit(Account theAcc, int amt) public void doDebit(Account theAcc, int amt) public void run() public boolean isBusy() /done with transactions?,Driver Class,public class BankOperation public static void main(String args) / initialization (balance, transactionCo

37、unt) / create account, bank and clerks / create clerk1Thread and clerk2Thread and start them off / generate transactions of each type and pass them to the appropriate clerk / wait until clerks are done & output results,Running the Example,Original balance : $ 500Total credits : $1252Total debits : $

38、 852Final balance : $ 100Should be : $ 900 The problem: One operation is retrieving the account balance while another operation is still in the process of amending it.,Synchronization,The objective of synchronization is to make sure that when several threads need access to a shared resource, only on

39、e thread can access it at any given time. Use synchronized at the method level: declare methods to be synchronized block of code level: declare some code to be synchronized,Synchronizing Methods Bank_SyncM,One solution: declare the operations in class Bank as being synchronized see Bank_SyncM synchr

40、onized public void credit(Account theAcc, int amt) int balance = theAcc.getBalance(); balance = balance + amt; / update balancetheAcc.setBalance(balance); / put it back in the bank synchronized public void debit(Account theAcc, int amt) / same as above except for: balance = balance - amt,Synchronizi

41、ng Methods,Only one of the synchronized methods in a class object can be executing at any time. synchronized public void method1() / code for the method synchronized public void method2() / code for the method / can also have none synchronized methods which will operate the usual way (not “protected

42、”) synchronized public void method3() / code for the method ,Synchronizing Blocks of Code,Specify a block of statements in the program as synchronized:synchronized(myObject) statement; statement; . / synchronized with respect to myObject Any other statements in the program that are synchronized with

43、 myObject cannot execute while the above statements are executing.,Synchronizing Code Bank_SyncB,Other solution: declare the code in the methods to be synchronized see Bank_SyncB public void credit(Account theAcc, int amt) synchronized(the Acc) int balance = theAcc.getBalance(); public void debit(Ac

44、count theAcc, int amt) synchronized(the Acc) int balance = theAcc.getBalance(); ,Handling Multiple Accounts Bank_SyncB,Bank_SyncB handles multiple accounts Had we left the synchronization of the methods (rather than the block of code), no debit operation of any kind would have been able to be carrie

45、d out while a credit operation is in progress, and vice versa. Synchronization of a block of code prevents overlapping of operations on the same account, and that is what we want.,Thread Organization Tan95,The possible organization of threads: dispatcher/worker model: an idle worker thread is chosen by the dispatcher thread for the incoming job team model: each thread works on its own request pipeline model: threads cooperate with each other in a sequential fashion. see Figure,

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