Java语言程序设计(异常处理、线程、集合操作)ppt.ppt

上传人:za****8 文档编号:16079146 上传时间:2020-09-17 格式:PPT 页数:90 大小:434.52KB
收藏 版权申诉 举报 下载
Java语言程序设计(异常处理、线程、集合操作)ppt.ppt_第1页
第1页 / 共90页
Java语言程序设计(异常处理、线程、集合操作)ppt.ppt_第2页
第2页 / 共90页
Java语言程序设计(异常处理、线程、集合操作)ppt.ppt_第3页
第3页 / 共90页
资源描述:

《Java语言程序设计(异常处理、线程、集合操作)ppt.ppt》由会员分享,可在线阅读,更多相关《Java语言程序设计(异常处理、线程、集合操作)ppt.ppt(90页珍藏版)》请在装配图网上搜索。

1、1,Java语言程序设计,马 皓,2,异常和异常类 异常处理 创建异常,第六章 异常处理,3,软件程序肯定会发生错误/问题 what really matters is what happens after the error occurs. How is the error handled? Who handles it? Can the program recover, or should it just die? 从外部问题(硬盘、网络故障等)到编程错误(数组越界、引用空对象等) 致命错误 内存空间不足等错误(Error)导致程序异常中断 程序不能简单地恢复执行 非致命错误 数组越界等异

2、常(Exception)导致程序中断执行 程序在修正后可恢复执行,异常(Exception),4,Java语言中已定义或用户定义的某个异常类的对象 一个异常类代表一种异常事件 Java语言利用异常来使程序获得处理错误的能力(error-handling) 异常事件(Exceptional Event) An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.,异常,5,Java语言中用来处理异常的类 异常类的方法 构造

3、方法 public Exception() public Exception(String s) 常用方法 public String toString() public String getMessage() public void printStackTrace(),异常类,6,对异常的定义 Java语言中定义的异常类: IOException/NullPointerException 详细定义见Java文档中各个包的Exception Summary 用户定义自已所需的异常类,描述程序中出现的异常结果,第10讲 异常(Exception),class java.lang.Throwabl

4、e class java.lang.Error (严重的问题,但不需程序捕捉的错误) class java.lang.LinkageError . . class java.lang.VirtualMachineError class java.lang.InternalError class java.lang.OutOfMemoryError . . class java.lang.Exception(程序应该捕捉的错误) class java.lang.ClassNotFoundException class java.lang.RuntimeException (JVM正常运行时抛出的

5、错误) class java.lang.ArithmeticException . . class java.io.IOException class java.awt.AWTException class java.sql.SQLException . .,7,异常和异常类 异常处理 创建异常,第六章 异常处理,8,当一个Java程序的方法产生一个错误,该方法创造一个异常对象并将其交给运行系统 In Java terminology, creating an exception object and handing it to the runtime system is called thr

6、owing an exception(抛出异常) 运行系统从错误发生处开始寻找处理错误的程序段 The exception handler chosen is said to catch the exception(捕获异常) 捕获异常的过程可以沿方法调用的逆向顺序寻找,异常处理,9,异常处理器(exception handler) try catch finally 异常的抛出(throw),异常处理,10,何时会出现异常? 方法中已定义了异常的抛出,异常处理,import java.io.IOException; class jex3_3 public static void main(S

7、tring args) throws IOException char c; System.out.println(Please input a char: ); c = (char)System.in.read(); System.out.println(Received char= + c); ,public abstract int read() throws IOException,在程序编译的时候必须完成异常的处理,11,由于非预期的结果导致系统运行时产生异常,异常处理,class jex7_9 public static void main(String args) int a =

8、 0; int b = 24/a; ,java jex7_9 Exception in thread main“ java.lang.ArithmeticException: / by zero,class jex7_9 public static void main(String args) int i = Integer.parseInt(args0); System.out.println(i); ,java jex7_9 Exception in thread main“ java.lang.ArrayIndexOutOfBoundsException: 0,java jex7_9 a

9、 Exception in thread main“ java.lang.NumberFormatException: For input string: “a”,12,异常处理器(exception handler) try catch finally,异常处理,13,异常处理器(exception handler) try程序块 构造一个异常处理器,封装一些抛出异常的语句 try Java 语句块; /指一个或多个抛出异常的Java语句 ,异常(Exception),class Test public static void main(String args) char c = (char

10、)System.in.read(); System.out.println(c); ,import java.io.IOException; class Test public static void main(String args) try char c = (char)System.in.read(); System.out.println(c); catch (IOException e) System.out.println(e); ,unreported exception java.io.IOException; must be caught or declared to be

11、thrown char c = (char)System.in.read();,一个try语句必须带有至少一个catch语句块 或一个finally语句块,14,异常处理器(exception handler) try语句块定义了异常处理器的范围 catch语句块捕捉try语句块抛出的异常 try / Code that might generate exceptions catch(Type1 id1) / Handle exceptions of Type1 catch(Type2 id2) / Handle exceptions of Type2 catch(Type3 id3) / H

12、andle exceptions of Type3 / etc .,异常处理,import java.io.IOException; class Test public static void main(String args) try char c = (char)System.in.read(); System.out.println(c); catch (IOException e) System.out.println(e); ,try . . . catch (ArrayIndexOutOfBoundsException e) System.out.println(e); catch

13、 (IOException e) System.out.println(e); ,15,异常处理器(exception handler) finally语句块 Theres often some piece of code that you want to execute whether or not an exception is thrown within a try block. finally语句块在异常处理中是必须执行的语句块 清理现场 关闭打开的文件 关闭网络连接,异常处理,try / The guarded region: Dangerous activities / that

14、might throw A, B, or C catch(A a1) / Handler for situation A catch(B b1) / Handler for situation B catch(C c1) / Handler for situation C finally / Activities that happen every time ,16,异常的抛出 在一个方法中,抛出异常,同时捕捉 当有多个方法调用时,由特定(适当)的方法捕捉异常 被调用的方法主动抛出异常(throws),异常处理,import java.io.IOException; class Test st

15、atic char getChar() throws IOException char c = (char)System.in.read(); return c; public static void main(String args) try char c = getChar(); System.out.println(c); catch (IOException e) System.out.println(e); ,17,异常的抛出 主动抛出异常,异常处理,void parseObj(String s) throws NullPointerException if (s = null) t

16、hrow new NullPointerException(); ; ,18,异常和异常类 异常处理 创建异常,第六章 异常处理,19,使用Java语言已有的异常异常的抛出/捕捉 创建自已的异常异常的抛出/捕捉,创建异常,20,异常(Exception),class SimpleException extends Exception public class SimpleExceptionDemo public void f() throws SimpleException System.out.println(Throw SimpleException from f(); throw new

17、 SimpleException(); public static void main(String args) SimpleExceptionDemo sed = new SimpleExceptionDemo(); try sed.f(); catch(SimpleException e) System.out.println(e); System.out.println(Caught it!); ,运行结果: Throw SimpleException from f() SimpleException Caught it!,21,自定义异常 自定义异常类必须是java.lang.Exce

18、ption类的子类 java.lang.Exception类的两个构造方法 Exception() Constructs a new exception with null as its detail message. Exception(Stringmessage) Constructs a new exception with the specified detail message. 自定义异常类可以不定义构造方法 SimpleException() super(); 自定义异常类定义自已的构造方法,创建异常,22,定义自已的异常构造方法,创建异常,23,class MyExceptio

19、n extends Exception private int x; public MyException() public MyException(String msg) super(msg); public MyException(String msg, int x) super(msg); this.x = x; ,class ExtraFeatures public static void f() throws MyException System.out.println(Throws MyException from f(); throw new MyException(); pub

20、lic static void g() throws MyException System.out.println(Throws MyException from g(); throw new MyException(Originated in g(); public static void h() throws MyException System.out.println(Throws MyException from h(); throw new MyException(Originated in h(), 47); ,try f(); catch(MyException e) Syste

21、m.out.println(e); ,Throwing MyException from f() MyException,try g(); catch(MyException e) System.out.println(e); ,Throwing MyException from g() MyException: Originated in g(),Throwing MyException from h() MyException: Originated in h(),try h(); catch(MyException e) System.out.println(e); ,24,Quiz Q

22、uestion: Is the following code legal?,异常(Exception),try . finally . ,Answer: Yes, its legal. A try statement does not have to have a catch statement if it has a finally statement. If the code in the try statement has multiple exit points and no associated catch clauses, the code in the finally state

23、ment is executed no matter how the try block is exited.,25,Quiz Question: What exceptions can be caught by the following handler?,异常(Exception),catch (Exception e) . ,Answer: This handler catches exceptions of type Exception; therefore, it catches any exception. This can be a poor implementation bec

24、ause you are losing valuable information about the type of exception being thrown and making your code less efficient. As a result, the runtime system is forced to determine the type of exception before it can decide on the best recovery strategy.,26,Quiz Question: What exception types can be caught

25、 by the following handler?,异常(Exception),. catch (Exception e) . catch (ArithmeticException a) . ,Answer: This first handler catches exceptions of type Exception; therefore, it catches any exception, including ArithmeticException. The second handler could never be reached. This code will not compile

26、.,27,第六章 结束 !,28,第七章 线程,概述 线程的创建 两种方式 线程的同步 synchronized wait()/notifyAll()/notify() 线程的生命周期,29,概述,进程(Process) 程序(Program)的一次动态执行过程, 占用特定的地址空间 在某种程度上相互隔离的、独立运行的程序 多任务(Multitasking)操作系统将CPU时间动态地划分给每个进程,操作系统同时执行多个进程,每个进程独立运行 进程的查看 Windows系统: Ctrl+Alt+Del Unix系统: ps or top,30,概述,线程(Thread) 线程是进程中一个“单一的

27、连续控制流程” (a single sequential flow of control)/执行路径 一个进程可拥有多个并行的(concurrent)线程 一个进程中的线程共享相同的内存单元/内存地址空间可以访问相同的变量和对象,而且它们从同一堆中分配对象通信、数据交换、同步操作 轻量级进程(lightweight process),31,概述,Java语言中的线程 大多数现代的操作系统都支持线程 第一个在语言本身中显性地包含线程的主流编程语言,它没有把线程化看作是底层操作系统的工具 每个 Java 程序都至少有一个线程主线程 当一个 Java 程序启动时,JVM 会创建主线程,并在该线程中调

28、用程序的main()方法 JVM还创建了其它线程,如垃圾收集(garbage collection),32,概述,多线程(MultiThreading)语言 java.lang.Thread类 java.lang.Runnable接口 为什么? (用途) Client/Server设计中的服务器端, 如每个用户请求建立一个线程 图形用户界面(GUI)的设计中提高事件响应的灵敏度 从提高程序执行效率的考虑 利用多处理器系统 执行异步或后台处理等,33,初探线程,public class SimpleThread extends Thread public SimpleThread(String

29、str) super(str); public void run() for (int i = 0; i 8; i+) System.out.println(i + + getName(); try sleep(long)(Math.random() * 1000); catch (InterruptedException e) System.out.println(DONE! + getName(); ,概述,public class TwoThreadsDemo public static void main (String args) new SimpleThread(Jamaica).

30、start(); new SimpleThread(Fiji).start(); ,运行结果: 0 Jamaica 0 Fiji 1 Jamaica 1 Fiji 2 Jamaica 2 Fiji 3 Jamaica 4 Jamaica 5 Jamaica 3 Fiji 6 Jamaica 7 Jamaica 4 Fiji DONE! Jamaica 5 Fiji 6 Fiji 7 Fiji DONE! Fiji,java.lang.Thread public static void sleep(long millis) throws InterruptedException Causes t

31、he currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.,34,第七章 线程,概述 线程的创建 两种方式 线程的同步 synchronized wait()/notifyAll()/notify() 线程的生命周期,35,线程创建的两种方式 “Subclassing Thread and Overriding run” 继承java.lang.Thread类, 重写run()方法 “Implementing the Runnable

32、 Interface” 实现java.lang.Runnable接口 Runnable接口的唯一方法 public void run(),线程的创建,36,再探线程,线程的创建,public class TwoThreadsDemo public static void main (String args) new SimpleThread1(Jamaica).start(); new SimpleThread1(Fiji).start(); ,public class SimpleThread2 implements Runnable String name; public SimpleTh

33、read2 (String str) name = str; public void run() for (int i = 0; i 8; i+) System.out.println(i+ +name); try Thread.sleep(long)(Math.random()*1000); catch (InterruptedException e) System.out.println(DONE!+name); ,public class SimpleThread1 extends Thread public SimpleThread1(String str) super(str); p

34、ublic void run() for (int i = 0; i 8; i+) System.out.println(i+ +getName(); try sleep(long)(Math.random()*1000); catch (InterruptedException e) System.out.println(DONE!+getName(); ,public class TwoThreadsDemo public static void main (String args) SimpleThread2 a = new SimpleThread2(Jamaica); Thread

35、thread1 = new Thread(a); thread1.start(); SimpleThread2 b = new SimpleThread2(Fiji); Thread thread2 = new Thread(b); thread2.start(); ,java.lang.Thread public Thread(Stringname) public Thread(Runnabletarget) public final String getName() public static void sleep(longmillis) throws InterruptedExcepti

36、on,37,线程创建的两种方式 “Subclassing Thread and Overriding run” 继承Thread类, 重写run()方法 “Implementing the Runnable Interface” 实现Runnable接口 应用场合 当所定义的类为一个子类时,须利用Runnable接口,线程的创建,38,第七章 线程,概述 线程的创建 两种方式 线程的同步 synchronized wait()/notifyAll()/notify() 线程的生命周期,39,独立的(independent)、异步的(asynchronous) 线程 共享资源的访问 多个线程对同

37、一资源进行操作(读/写) 当多个线程访问同一数据项(如静态字段、可全局访问对象的实例字段或共享集合)时,需要确保它们协调了对数据的访问,这样它们都可以看到数据的一致视图,而且相互不会干扰另一方的更改 synchronized 关键词 wait() / notify() / notifyAll() 方法,线程的同步,40,线程同步-实例,线程的同步,public class CubbyHole private int contents; public int get() return contents; public void put(int value) contents = value; ,

38、public class Producer extends Thread private CubbyHole cubbyhole; public Producer(CubbyHole c) cubbyhole = c; public void run() for (int i = 0; i 10; i+) cubbyhole.put(i); System.out.println(Producer + put: + i); try sleep(int)(Math.random() * 100); catch (InterruptedException e) ,public class Consu

39、mer extends Thread private CubbyHole cubbyhole; public Consumer(CubbyHole c) cubbyhole = c; public void run() int value = 0; for (int i = 0; i 10; i+) value = cubbyhole.get(); System.out.println(Consumer “ + got: + value); ,public class ProducerConsumerTest public static void main(String args) Cubby

40、Hole h = new CubbyHole(); Producer p = new Producer(h); Consumer c = new Consumer(h); p.start(); c.start(); ,. . . Consumer got: 3 Producer put: 4 Producer put: 5 Consumer got: 5 . . .,. . . Producer put: 4 Consumer got: 4 Consumer got: 4 Producer put: 5 . . .,41,给关键部分(Critical Section)加锁(lock) Cubb

41、yHole对象 synchronized 关键词the two threads must not simultaneously access the CubbyHole. The Java platform then associates a lock with every object that has synchronized code,线程的同步,public class CubbyHole private int contents; public int get() return contents; public void put(int value) contents = value

42、; ,public class CubbyHole private int contents; public synchronized int get() return contents; public synchronized void put(int value) contents = value; ,42,线程的协调 the two threads must do some simple coordination. Producer通过某种方式告诉Consumer在CubbyHole中有值,而 Consumer必须通过某种方式表示出CubbyHole中的值已被取走 CubbyHole对象

43、 (Critical Section) java.lang.Object类的方法 wait()、notify()、notifyAll(),线程的同步,43,线程的同步,public class CubbyHole private int contents; public int get() return contents; public void put(int value) contents = value; ,public class CubbyHole private int contents; private boolean available = false; public sync

44、hronized int get() while (available = false) try wait(); /打开锁,等候Producer填值 catch (InterruptedException e) available = false; notifyAll(); return contents; public synchronized void put(int value) while (available = true) try wait(); /打开锁,等候Consumer取值 catch (InterruptedException e) contents = value; a

45、vailable = true; notifyAll(); ,java.lang.Object public final void wait() throws InterruptedException public final void wait(long timeout) throws InterruptedException public final void notifyAll() /唤醒所有等待的线程 public final void notify() /随机唤醒一个等待的线程,The wait method relinquishes the lock held by the Con

46、sumer on the CubbyHole (thereby allowing the Producer to get the lock and update the CubbyHole) and then waits for notification from the Producer.,44,线程的同步,public class CubbyHole private int contents; private boolean available = false; public synchronized int get() while (available = false) try wait

47、(); /打开锁,等候Producer填值 catch (InterruptedException e) available = false; notifyAll(); return contents; public synchronized void put(int value) while (available = true) try wait(); /打开锁,等候Consumer取值 catch (InterruptedException e) contents = value; available = true; notifyAll(); ,线程 consumer,get(),判断当前

48、是否存有值,有,没有,设置为空 唤醒producer 取值,释放锁定 等待新值,线程 producer,put(),判断当前是否存有值,有,没有,释放锁定 等待取值,放值 设置为有 唤醒consumer,45,第七章 线程,概述 线程的创建 两种方式 线程的同步 synchronized wait()/notifyAll()/notify() 线程的生命周期,46,线程启动 new SimpleThread1(Jamaica).start(); class SimpleThread1 extends Thread SimpleThread2 a = new SimpleThread2(Jama

49、ica); Thread thread = new Thread(a); thread.start(); class SimpleThread2 implements Runnable 线程停止 A thread dies naturally when the run method exits.,线程的生命周期,public void run() int i = 0; while (i 100) i+; System.out.println(i = + i); ,47,进一步的学习 Starvation (资源缺乏) Deadlock (死锁) ThreadGroup (线程组) 同时对一组线

50、程进行操作 优先权 (Priorities) Daemon线程,线程,48,第七章 结束!,49,对数组对象的操作(Arrays) 对象集合(Set) 对象列表(List) 对象映射(Map) 对对象数组的操作(Collections) 枚举(Enumeration)和迭代(Iterator) 小结,集合操作,50,java.util.Arrays类 This class contains various methods for manipulating arrays 排序(sorting) 搜索(searching) 填充(filling),对数组对象的操作(Arrays),51,全部是静态

51、方法 public static int binarySearch(byte a, byte key) Searches the specified array of bytes for the specified value using the binary search algorithm. public static boolean equals(byte a, byte a2) Returns true if the two specified arrays of bytes are equal to one another. public static void fill(byte

52、a, byte val) Assigns the specified byte value to each element of the specified array of bytes. public static void fill(byte a, int fromIndex, int toIndex, byte val) Assigns the specified byte value to each element of the specified range of the specified array of bytes. public static void sort(byte a

53、) Sorts the specified array of bytes into ascending numerical order.,对数组对象的操作(Arrays),boolean, char, byte, short, int, long, double, float Object,52,对数组对象的操作(Arrays),import java.util.Arrays; public class ArrayDemo1 public static void main(String args) int a1 = new int10; int a2 = new int10; Arrays.f

54、ill(a1, 47); Arrays.fill(a2, 47); System.out.println(Arrays.equals(a1, a2); a23=11; a22=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)

55、 小结,集合操作,54,数学上“集合”概念的抽象,无序 A Set is a collection that cannot contain duplicate elements. 集合与元素 集合之间 无序集合和有序集合,对象集合(Set),55,java.util.Set 接口 (集合与元素) public boolean add(Object o) Adds the specified element to this set if it is not already present. public boolean remove(Object o) Removes the specified

56、 element from this set if it is present. public boolean contains(Object o) Returns true if this set contains the specified element. public int size() Returns the number of elements in this set.,对象集合(Set),56,java.util.HashSet implement java.util.Set 无序集合,对象集合(Set),import java.util.*; public class Set

57、Demo1 public static void main(String args) Set s = new HashSet(); for (int i=0; iargs.length; i+) if (!s.add(argsi) System.out.println(Duplicate: +argsi); System.out.println(s.size()+ distinct words: +s); ,D:java FindDups1 i came i saw i left Duplicate: i Duplicate: i 4 distinct words: came, left, s

58、aw, i D:,57,java.util.Set接口 (集合之间) public boolean containsAll(Collection c) Returns true if this set contains all of the elements of the specified collection. public boolean addAll(Collection c) Adds all of the elements in the specified collection to this set if theyre not already present. public bo

59、olean removeAll(Collection c) Removes from this set all of its elements that are contained in the specified collection. public boolean retainAll(Collection c) Retains only the elements in this set that are contained in the specified collection.,对象集合(Set),58,java.util.HashSet implement java.util.Set,

60、对象集合(Set),import java.util.*; public class SetDemo2 public static void main(String args) Set uniques = new HashSet(); Set dups = new HashSet(); for (int i=0; iargs.length; i+) if (!uniques.add(argsi) dups.add(argsi); uniques.removeAll(dups); System.out.println(Unique words: + uniques); System.out.pr

61、intln(Duplicate words: + dups); ,D:java FindDups2 i came i saw i left Unique words: came, left, saw Duplicate words: i D:,59,HashSet(无序集合),对象集合(Set),import java.util.*; public class SetDemo3 public static void main(String args) boolean b; Set s = new HashSet(); b = s.add(string1); System.out.println

62、(string1 add returns + b); b = s.add(string2); System.out.println(string2 add returns + b); b = s.add(string3); System.out.println(string3 add returns + b); b = s.add(string1); System.out.println(string1 add returns + b); b = s.add(string2); System.out.println(string2 add returns + b); Iterator i =

63、s.iterator(); while (i.hasNext() System.out.println(i.next(); ,D:java SetDemo3 string1 add returns true string2 add returns true string3 add returns true string1 add returns false string2 add returns false string3 string1 string2 D:,java.util.Iterator 迭代器(interface) 轮循,无序输出,60,对象集合(Set),java.util.Se

64、t (interface),java.util.SortedSet (interface),java.util.HashSet (class),java.util.TreeSet (class),无序集合,有序集合,HashSet: Set implemented via a hash table TreeSet: SortedSet implemented as a tree,61,java.util.TreeSet implement java.util.SortedSet,对象集合(Set),import java.util.*; public class SetDemo4 public static void main(String args) boolean b; Set s = new TreeSet(); b = s.add(string1); System.out.println(string1 add returns + b); b = s.add(string2);

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

copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!