Java语言程序设计(异常处理、线程、集合操作)ppt.ppt_第1页
Java语言程序设计(异常处理、线程、集合操作)ppt.ppt_第2页
Java语言程序设计(异常处理、线程、集合操作)ppt.ppt_第3页
Java语言程序设计(异常处理、线程、集合操作)ppt.ppt_第4页
Java语言程序设计(异常处理、线程、集合操作)ppt.ppt_第5页
已阅读5页,还剩85页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1 Java语言程序设计 马皓 2 异常和异常类异常处理创建异常 第六章异常处理 3 软件程序肯定会发生错误 问题whatreallymattersiswhathappensaftertheerroroccurs Howistheerrorhandled Whohandlesit Cantheprogramrecover orshoulditjustdie 从外部问题 硬盘 网络故障等 到编程错误 数组越界 引用空对象等 致命错误内存空间不足等错误 Error 导致程序异常中断程序不能简单地恢复执行非致命错误数组越界等异常 Exception 导致程序中断执行程序在修正后可恢复执行 异常 Exception 4 Java语言中已定义或用户定义的某个异常类的对象一个异常类代表一种异常事件Java语言利用异常来使程序获得处理错误的能力 error handling 异常事件 ExceptionalEvent Anexceptionisaneventthatoccursduringtheexecutionofaprogramthatdisruptsthenormalflowofinstructions 异常 5 Java语言中用来处理异常的类异常类的方法构造方法publicException publicException Strings 常用方法publicStringtoString publicStringgetMessage publicvoidprintStackTrace 异常类 6 对异常的定义Java语言中定义的异常类 IOException NullPointerException详细定义见Java文档中各个包的ExceptionSummary用户定义自已所需的异常类 描述程序中出现的异常结果 第10讲异常 Exception classjava lang Throwableclassjava lang Error 严重的问题 但不需程序捕捉的错误 classjava lang LinkageError classjava lang VirtualMachineErrorclassjava lang InternalErrorclassjava lang OutOfMemoryError classjava lang Exception 程序应该捕捉的错误 classjava lang ClassNotFoundExceptionclassjava lang RuntimeException JVM正常运行时抛出的错误 classjava lang ArithmeticException classjava io IOExceptionclassjava awt AWTExceptionclassjava sql SQLException 7 异常和异常类异常处理创建异常 第六章异常处理 8 当一个Java程序的方法产生一个错误 该方法创造一个异常对象并将其交给运行系统InJavaterminology creatinganexceptionobjectandhandingittotheruntimesystemiscalledthrowinganexception 抛出异常 运行系统从错误发生处开始寻找处理错误的程序段Theexceptionhandlerchosenissaidtocatchtheexception 捕获异常 捕获异常的过程可以沿方法调用的逆向顺序寻找 异常处理 9 异常处理器 exceptionhandler trycatchfinally异常的抛出 throw 异常处理 10 何时会出现异常 方法中已定义了异常的抛出 异常处理 importjava io IOException classjex3 3 publicstaticvoidmain Stringargs throwsIOException charc System out println Pleaseinputachar c char System in read System out println Receivedchar c publicabstractintread throwsIOException 在程序编译的时候必须完成异常的处理 11 由于非预期的结果导致系统运行时产生异常 异常处理 classjex7 9 publicstaticvoidmain Stringargs inta 0 intb 24 a javajex7 9Exceptioninthread main java lang ArithmeticException byzero classjex7 9 publicstaticvoidmain Stringargs inti Integer parseInt args 0 System out println i javajex7 9Exceptioninthread main java lang ArrayIndexOutOfBoundsException 0 javajex7 9aExceptioninthread main java lang NumberFormatException Forinputstring a 12 异常处理器 exceptionhandler trycatchfinally 异常处理 13 异常处理器 exceptionhandler try程序块构造一个异常处理器 封装一些抛出异常的语句try Java语句块 指一个或多个抛出异常的Java语句 异常 Exception classTest publicstaticvoidmain Stringargs charc char System in read System out println c importjava io IOException classTest publicstaticvoidmain Stringargs try charc char System in read System out println c catch IOExceptione System out println e unreportedexceptionjava io IOException mustbecaughtordeclaredtobethrowncharc char System in read 一个try语句必须带有至少一个catch语句块或一个finally语句块 14 异常处理器 exceptionhandler try语句块定义了异常处理器的范围catch语句块捕捉try语句块抛出的异常try Codethatmightgenerateexceptions catch Type1id1 HandleexceptionsofType1 catch Type2id2 HandleexceptionsofType2 catch Type3id3 HandleexceptionsofType3 etc 异常处理 importjava io IOException classTest publicstaticvoidmain Stringargs try charc char System in read System out println c catch IOExceptione System out println e try catch ArrayIndexOutOfBoundsExceptione System out println e catch IOExceptione System out println e 15 异常处理器 exceptionhandler finally语句块There softensomepieceofcodethatyouwanttoexecutewhetherornotanexceptionisthrownwithinatryblock finally语句块在异常处理中是必须执行的语句块清理现场关闭打开的文件关闭网络连接 异常处理 try Theguardedregion Dangerousactivities thatmightthrowA B orC catch Aa1 HandlerforsituationA catch Bb1 HandlerforsituationB catch Cc1 HandlerforsituationC finally Activitiesthathappeneverytime 16 异常的抛出在一个方法中 抛出异常 同时捕捉当有多个方法调用时 由特定 适当 的方法捕捉异常被调用的方法主动抛出异常 throws 异常处理 importjava io IOException classTest staticchargetChar throwsIOException charc char System in read returnc publicstaticvoidmain Stringargs try charc getChar System out println c catch IOExceptione System out println e 17 异常的抛出主动抛出异常 异常处理 voidparseObj Strings throwsNullPointerException if s null thrownewNullPointerException 18 异常和异常类异常处理创建异常 第六章异常处理 19 使用Java语言已有的异常 异常的抛出 捕捉创建自已的异常 异常的抛出 捕捉 创建异常 20 异常 Exception classSimpleExceptionextendsException publicclassSimpleExceptionDemo publicvoidf throwsSimpleException System out println ThrowSimpleExceptionfromf thrownewSimpleException publicstaticvoidmain String args SimpleExceptionDemosed newSimpleExceptionDemo try sed f catch SimpleExceptione System out println e System out println Caughtit 运行结果 ThrowSimpleExceptionfromf SimpleExceptionCaughtit 21 自定义异常自定义异常类必须是java lang Exception类的子类java lang Exception类的两个构造方法Exception Constructsanewexceptionwithnullasitsdetailmessage Exception Stringmessage Constructsanewexceptionwiththespecifieddetailmessage 自定义异常类可以不定义构造方法SimpleException super 自定义异常类定义自已的构造方法 创建异常 22 定义自已的异常构造方法 创建异常 23 classMyExceptionextendsException privateintx publicMyException publicMyException Stringmsg super msg publicMyException Stringmsg intx super msg this x x classExtraFeatures publicstaticvoidf throwsMyException System out println ThrowsMyExceptionfromf thrownewMyException publicstaticvoidg throwsMyException System out println ThrowsMyExceptionfromg thrownewMyException Originateding publicstaticvoidh throwsMyException System out println ThrowsMyExceptionfromh thrownewMyException Originatedinh 47 try f catch MyExceptione System out println e ThrowingMyExceptionfromf MyException try g catch MyExceptione System out println e ThrowingMyExceptionfromg MyException Originateding ThrowingMyExceptionfromh MyException Originatedinh try h catch MyExceptione System out println e 24 QuizQuestion Isthefollowingcodelegal 异常 Exception try finally Answer Yes it slegal Atrystatementdoesnothavetohaveacatchstatementifithasafinallystatement Ifthecodeinthetrystatementhasmultipleexitpointsandnoassociatedcatchclauses thecodeinthefinallystatementisexecutednomatterhowthetryblockisexited 25 QuizQuestion Whatexceptionscanbecaughtbythefollowinghandler 异常 Exception catch Exceptione Answer ThishandlercatchesexceptionsoftypeException therefore itcatchesanyexception Thiscanbeapoorimplementationbecauseyouarelosingvaluableinformationaboutthetypeofexceptionbeingthrownandmakingyourcodelessefficient Asaresult theruntimesystemisforcedtodeterminethetypeofexceptionbeforeitcandecideonthebestrecoverystrategy 26 QuizQuestion Whatexceptiontypescanbecaughtbythefollowinghandler 异常 Exception catch Exceptione catch ArithmeticExceptiona Answer ThisfirsthandlercatchesexceptionsoftypeException therefore itcatchesanyexception includingArithmeticException Thesecondhandlercouldneverbereached Thiscodewillnotcompile 27 第六章结束 28 第七章线程 概述线程的创建两种方式线程的同步synchronizedwait notifyAll notify 线程的生命周期 29 概述 进程 Process 程序 Program 的一次动态执行过程 占用特定的地址空间在某种程度上相互隔离的 独立运行的程序多任务 Multitasking 操作系统 将CPU时间动态地划分给每个进程 操作系统同时执行多个进程 每个进程独立运行进程的查看Windows系统 Ctrl Alt DelUnix系统 psortop 30 概述 线程 Thread 线程是进程中一个 单一的连续控制流程 asinglesequentialflowofcontrol 执行路径一个进程可拥有多个并行的 concurrent 线程一个进程中的线程共享相同的内存单元 内存地址空间 可以访问相同的变量和对象 而且它们从同一堆中分配对象 通信 数据交换 同步操作轻量级进程 lightweightprocess 31 概述 Java语言中的线程大多数现代的操作系统都支持线程第一个在语言本身中显性地包含线程的主流编程语言 它没有把线程化看作是底层操作系统的工具每个Java程序都至少有一个线程 主线程当一个Java程序启动时 JVM会创建主线程 并在该线程中调用程序的main 方法JVM还创建了其它线程 如垃圾收集 garbagecollection 32 概述 多线程 MultiThreading 语言java lang Thread类java lang Runnable接口为什么 用途 Client Server设计中的服务器端 如每个用户请求建立一个线程图形用户界面 GUI 的设计中提高事件响应的灵敏度从提高程序执行效率的考虑利用多处理器系统执行异步或后台处理等 33 初探线程 publicclassSimpleThreadextendsThread publicSimpleThread Stringstr super str publicvoidrun for inti 0 i 8 i System out println i getName try sleep long Math random 1000 catch InterruptedExceptione System out println DONE getName 概述 publicclassTwoThreadsDemo publicstaticvoidmain String args newSimpleThread Jamaica start newSimpleThread Fiji start 运行结果 0Jamaica0Fiji1Jamaica1Fiji2Jamaica2Fiji3Jamaica4Jamaica5Jamaica3Fiji6Jamaica7Jamaica4FijiDONE Jamaica5Fiji6Fiji7FijiDONE Fiji java lang Threadpublicstaticvoidsleep longmillis throwsInterruptedExceptionCausesthecurrentlyexecutingthreadtosleep temporarilyceaseexecution forthespecifiednumberofmilliseconds 34 第七章线程 概述线程的创建两种方式线程的同步synchronizedwait notifyAll notify 线程的生命周期 35 线程创建的两种方式 SubclassingThreadandOverridingrun 继承java lang Thread类 重写run 方法 ImplementingtheRunnableInterface 实现java lang Runnable接口Runnable接口的唯一方法publicvoidrun 线程的创建 36 再探线程 线程的创建 publicclassTwoThreadsDemo publicstaticvoidmain String args newSimpleThread1 Jamaica start newSimpleThread1 Fiji start publicclassSimpleThread2implementsRunnable Stringname publicSimpleThread2 Stringstr name str publicvoidrun for inti 0 i 8 i System out println i name try Thread sleep long Math random 1000 catch InterruptedExceptione System out println DONE name publicclassSimpleThread1extendsThread publicSimpleThread1 Stringstr super str publicvoidrun for inti 0 i 8 i System out println i getName try sleep long Math random 1000 catch InterruptedExceptione System out println DONE getName publicclassTwoThreadsDemo publicstaticvoidmain String args SimpleThread2a newSimpleThread2 Jamaica Threadthread1 newThread a thread1 start SimpleThread2b newSimpleThread2 Fiji Threadthread2 newThread b thread2 start java lang ThreadpublicThread Stringname publicThread Runnabletarget publicfinalStringgetName publicstaticvoidsleep longmillis throwsInterruptedException 37 线程创建的两种方式 SubclassingThreadandOverridingrun 继承Thread类 重写run 方法 ImplementingtheRunnableInterface 实现Runnable接口应用场合当所定义的类为一个子类时 须利用Runnable接口 线程的创建 38 第七章线程 概述线程的创建两种方式线程的同步synchronizedwait notifyAll notify 线程的生命周期 39 独立的 independent 异步的 asynchronous 线程共享资源的访问多个线程对同一资源进行操作 读 写 当多个线程访问同一数据项 如静态字段 可全局访问对象的实例字段或共享集合 时 需要确保它们协调了对数据的访问 这样它们都可以看到数据的一致视图 而且相互不会干扰另一方的更改synchronized关键词wait notify notifyAll 方法 线程的同步 40 线程同步 实例 线程的同步 publicclassCubbyHole privateintcontents publicintget returncontents publicvoidput intvalue contents value publicclassProducerextendsThread privateCubbyHolecubbyhole publicProducer CubbyHolec cubbyhole c publicvoidrun for inti 0 i 10 i cubbyhole put i System out println Producer put i try sleep int Math random 100 catch InterruptedExceptione publicclassConsumerextendsThread privateCubbyHolecubbyhole publicConsumer CubbyHolec cubbyhole c publicvoidrun intvalue 0 for inti 0 i 10 i value cubbyhole get System out println Consumer got value publicclassProducerConsumerTest publicstaticvoidmain String args CubbyHoleh newCubbyHole Producerp newProducer h Consumerc newConsumer h p start c start Consumergot 3Producerput 4Producerput 5Consumergot 5 Producerput 4Consumergot 4Consumergot 4Producerput 5 41 给关键部分 CriticalSection 加锁 lock CubbyHole对象synchronized关键词 thetwothreadsmustnotsimultaneouslyaccesstheCubbyHole TheJavaplatformthenassociatesalockwitheveryobjectthathassynchronizedcode 线程的同步 publicclassCubbyHole privateintcontents publicintget returncontents publicvoidput intvalue contents value publicclassCubbyHole privateintcontents publicsynchronizedintget returncontents publicsynchronizedvoidput intvalue contents value 42 线程的协调thetwothreadsmustdosomesimplecoordination Producer通过某种方式告诉Consumer在CubbyHole中有值 而Consumer必须通过某种方式表示出CubbyHole中的值已被取走CubbyHole对象 CriticalSection java lang Object类的方法wait notify notifyAll 线程的同步 43 线程的同步 publicclassCubbyHole privateintcontents publicintget returncontents publicvoidput intvalue contents value publicclassCubbyHole privateintcontents privatebooleanavailable false publicsynchronizedintget while available false try wait 打开锁 等候Producer填值 catch InterruptedExceptione available false notifyAll returncontents publicsynchronizedvoidput intvalue while available true try wait 打开锁 等候Consumer取值 catch InterruptedExceptione contents value available true notifyAll java lang Objectpublicfinalvoidwait throwsInterruptedExceptionpublicfinalvoidwait longtimeout throwsInterruptedExceptionpublicfinalvoidnotifyAll 唤醒所有等待的线程publicfinalvoidnotify 随机唤醒一个等待的线程 ThewaitmethodrelinquishesthelockheldbytheConsumerontheCubbyHole therebyallowingtheProducertogetthelockandupdatetheCubbyHole andthenwaitsfornotificationfromtheProducer 44 线程的同步 publicclassCubbyHole privateintcontents privatebooleanavailable false publicsynchronizedintget while available false try wait 打开锁 等候Producer填值 catch InterruptedExceptione available false notifyAll returncontents publicsynchronizedvoidput intvalue while available true try wait 打开锁 等候Consumer取值 catch InterruptedExceptione contents value available true notifyAll 线程consumer get 判断当前是否存有值 有 没有 设置为空唤醒producer取值 释放锁定等待新值 线程producer put 判断当前是否存有值 有 没有 释放锁定等待取值 放值设置为有唤醒consumer 45 第七章线程 概述线程的创建两种方式线程的同步synchronizedwait notifyAll notify 线程的生命周期 46 线程启动newSimpleThread1 Jamaica start classSimpleThread1extendsThread SimpleThread2a newSimpleThread2 Jamaica Threadthread newThread a thread start classSimpleThread2implementsRunnable 线程停止Athreaddiesnaturallywhentherunmethodexits 线程的生命周期 publicvoidrun inti 0 while i 100 i System out println i i 47 进一步的学习Starvation 资源缺乏 Deadlock 死锁 ThreadGroup 线程组 同时对一组线程进行操作优先权 Priorities Daemon线程 线程 48 第七章结束 49 对数组对象的操作 Arrays 对象集合 Set 对象列表 List 对象映射 Map 对对象数组的操作 Collections 枚举 Enumeration 和迭代 Iterator 小结 集合操作 50 java util Arrays类Thisclasscontainsvariousmethodsformanipulatingarrays排序 sorting 搜索 searching 填充 filling 对数组对象的操作 Arrays 51 全部是静态方法publicstaticintbinarySearch byte a bytekey Searchesthespecifiedarrayofbytesforthespecifiedvalueusingthebinarysearchalgorithm publicstaticbooleanequals byte a byte a2 Returnstrueifthetwospecifiedarraysofbytesareequaltooneanother publicstaticvoidfill byte a byteval Assignsthespecifiedbytevaluetoeachelementofthespecifiedarrayofbytes publicstaticvoidfill byte a intfromIndex inttoIndex byteval Assignsthespecifiedbytevaluetoeachelementofthespecifiedrangeofthespecifiedarrayofbytes publicstaticvoidsort byte a Sortsthespecifiedarrayofbytesintoascendingnumericalorder 对数组对象的操作 Arrays boolean char byte short int long double float Object 52 对数组对象的操作 Arrays importjava util Arrays publicclassArrayDemo1 publicstaticvoidmain Stringargs int a1 newint 10 int a2 newint 10 Arrays fill a1 47 Arrays fill a2 47 System out println Arrays equals a1 a2 a2 3 11 a2 2 9 System out println Arrays equals a1 a2 Arrays sort a2 System out println Arrays binarySearch a2 11 53 对数组对象的操作 Arrays 对象集合 Set 对象列表 List 对象映射 Map 对对象数组的操作 Collections 枚举 Enumeration 和迭代 Iterator 小结 集合操作 54 数学上 集合 概念的抽象 无序ASetisacollectionthatcannotcontainduplicateelements 集合与元素集合之间无序集合和有序集合 对象集合 Set 55 java util Set接口 集合与元素 publicbooleanadd Objecto Addsthespecifiedelementtothissetifitisnotalreadypresent publicbooleanremove Objecto Removesthespecifiedelementfromthissetifitispresent publicbooleancontains Objecto Returnstrueifthissetcontainsthespecifiedelement publicintsize Returnsthenumberofelementsinthisset 对象集合 Set 56 java util HashSetimplementjava util Set无序集合 对象集合 Set importjava util publicclassSetDemo1 publicstaticvoidmain Stringargs Sets newHashSet for inti 0 i args length i if s add args i System out println Duplicate args i System out println s size distinctwords s D javaFindDups1icameisawileftDuplicate iDuplicate i4distinctwords came left saw i D 57 java util Set接口 集合之间 publicbooleancontainsAll Collectionc Returnstrueifthissetcontainsalloftheelementsofthespecifiedcollection publicbooleanaddAll Collectionc Addsalloftheelementsinthespecifiedcollectiontothissetifthey renotalreadypresent publicbooleanremoveAll Collectionc Removesfromthissetallofitselementsthatarecontainedinthespecifiedcollection publicbooleanretainAll Collectionc Retainsonlytheelementsinthissetthatarecontainedinthespecifiedcollection 对象集合 Set 58 java util HashSetimplementjava util Set 对象集合 Set importjava util publicclassSetDemo2 publicstaticvoidmain Stringargs Setuniques newHashSet Setdups newHashSet for inti 0 i args length i if uniques add args i dups add args i uniques removeAll dups System out println Uniquewords uniques System out println Duplicatewords dups D javaFindDups2icameisawileftUniquewords came left saw Duplicatewords i D 59 HashSet 无序集合 对象集合 Set importjava util publicclassSetDemo3 publicstaticvoidmain Stringargs booleanb Sets newHashSet b s add string1 System out println string1addreturns b b s add string2 System out println string2addreturns b b s add string3 System out println string3addreturns b b s add string1 System out println string1addreturns b b s add string2 System out println string2addreturns b Iteratori s iterator while i hasNext System out println i next D javaSetDemo3string1addreturnstruestring2addreturnstruestring3addreturnstruestring1addreturnsfalsestring2addreturnsfalsestring3string1string2D java util Iterator迭代器 interface 轮循 无序输出 60 对象集合 Set java util Set interface java util SortedSet interface java util HashSet class java util TreeSet class 无序集合 有序集合 HashSet SetimplementedviaahashtableTreeSet SortedSetimplementedasatree 61 java util TreeSetimplementjava util SortedSet 对象集合 Set importjava util publicclassSetDemo4 publicstaticvoidmain Stringargs booleanb Sets newTreeSet b s add string1 System out println string1addreturns b b s add string2 System out println string2addreturns b b s add string3 System out println string3addreturns b b s add string1 System out println string1addreturns b b s add string2 System out println string2addreturns b Iteratori s iterator while i hasNext System out println i next D javaSetDemo4string1addreturnstruestring2addreturnstruestring3addreturnstruestring1addreturnsfalsestring2addreturnsfalsestring1string2string3D java util Iterator迭代器 interface 轮循 有序输出 自然顺序 62 对象集合 Set importjava util publicclassSetDemo5 publicstaticvoidmain Stringargs Sets newHashSet s add 37 s add newInteger 37 Iteratori s iterator while i hasNext System out println i next createasetandaddtwoobjectstoit theobjectsaredistinctbuthavethesamedisplayablestring D javaSetDemo53737D 63 对象集合 Set importjava util publicclassSetDemo6 publicstaticvoidmain Stringargs Sets newTreeSet s add 37 s add newInteger 37 Iteratori s iterator while i hasNext System out println i next createaSortedSet addtwoobjectstotheset theobjectsarenotcomparable D javaSetDemo6Exceptioninthread main java lang ClassCastExceptionD Theexceptionisthrownbecauseanattemptismadetoordertheelementsoftheset AStringobjecthasnorelationshiptoanIntegerobject sotherelativeo

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论