已阅读5页,还剩31页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
第21章 泛型 Genericswildcard通配符? unbounded wildcard 非受限通配符 ? extends T bounded wildcard 受限通配符? super T lower bound wildcard 下限通配符泛型是参数化类型的能力。表示形式泛型类型,后面可以用一个实际具体类型代替它。泛型类型必须是引用类型受限泛型类型bounded wildcard public static void main(String args ) Rectangle rectangle = new Rectangle(2, 2); Circle9 circle = new Circle9(2); System.out.println(Same area? + equalArea(rectangle, circle);public static boolean equalArea(E object1, E object2) return object1.findArea() = object2.findArea();Raw Type is Unsafe:GenericStack stack = new GenericStack(); / 原始类型Make it safe:GenericStack stack = new GenericStack(); It is important to note that a generic class is shared by all its instances regardless of its actual generic type. 不管实际的具体类型是什么,一个泛型是由其所有实例共享的. GenericStack stack1 = new GenericStack();GenericStack stack2 = new GenericStack();Although GenericStack and GenericStack are two types, but there is only one class GenericStack loaded into the JVM.尽管GenericStack 和 GenericStack 是两种类型, 但是只有一个 GenericStack 类加载到 JVM. 第22章 集合构架 Java collection frameworkA collection is a container object that represents a group of objects, often referred to as elements. The Java Collections Framework supports three types of collections, named sets, lists, and maps.Set and List are subinterfaces of Collection.The Set interface extends the Collection interface. It does not introduce new methods or constants, but it stipulates保证 that an instance of Set contains no duplicate 重复的elements. The concrete classes 具体类that implement Set must ensure that no duplicate重复的 elements can be added to the set. That is no two elements e1 and e2 can be in the set such that e1.equals(e2) is true.set规则集中元素互异,不得重复。The AbstractSet class is a convenience class that extends AbstractCollection and implements Set.The HashSet class is a concrete class that implements Set.HashSet 类是一个实现Set接口的具体类。It can be used to store duplicate-free elements. 可以存储互不相同的元素For efficiency, objects added to a hash set need to implement the hashCode method in a manner that properly disperses the hash code. 添加到散列集中的对象必须实现hashCode方法,适当地散列分布散列码。for (Object element: set) System.out.print(element.toString() + );SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted. TreeSet is a concrete class that implements the SortedSet interface. You can use an iterator to traverse the elements in the sorted order. The elements can be sorted in two ways. One way is to use the Comparable interface. The other way is to specify a comparator for the elements in the set if the class for the elements does not implement the Comparable interface, or you dont want to use the compareTo method in the class that implements the Comparable interface. This approach is referred to as order by comparator.有2种方法可以实现比较:使用Comparable接口中的compareTo方法。给规则集的元素指定一个比较器。TreeSet 是实现SortedSet接口的一个具体类,只有当对象之间可以相互比较时,才可以将他们添加到树形集TreeSet中。有时想把不同类型的元素添加到同一个树形集合内,这些元素可能是不能相互比较的,这时可以定义一个比较器来比较这些元素。Comparator 接口有2个方法, compare and equals.public int compare(Object element1, Object element2)Returns a negative value if element1 is less than element2, a positive value if element1 is greater than element2, and zero if they are equal. public boolean equals(Object element)Returns true if the specified指定的 object is also a comparator比较器 and imposes利用 the same ordering as this comparator.A list can not only store duplicate elements, but can also allow the user to specify where the element is stored. The user can access the element by index. 线性表不仅支持重复的存储,而且支持用户指定它们的存储位置。The ArrayList class and the LinkedList class are concrete implementations of the List interface. 数组线性表ArrayList 和链表 LinkedList是实现List接口的2个具体类。ArrayList:you need to support random access through an index without inserting or removing elements from any place other than the end.choose LinkedList,your application requires the insertion or deletion of elements from any place in the listA list can grow or shrink dynamically. An array is fixed once it is created. If your application does not require insertion or deletion of elements, the most efficient data structure is the array.数组线性表ArrayList将元素存储在一个数组中,该数组是动态创建的。超过数组的容量时,则创建一个更大的数组并把当前数组中的所有元素复制到新数组中。链表 LinkedList将元素存储在链表中。In Java 2, Vector 向量类is the same as ArrayList, except that Vector contains the synchronized methods 同步方法for accessing and modifying 访问和修改向量the vector.在Java 2中,Vector类除了包含用于访问和修改向量的同步方法之外,它与ArrayList是相同的。同步方法用于防止两个或多个线程同时访问向量时引起数据冲突。The Stack class represents a last-in-first-out后进先出(LIFO)stack of objects. The elements are accessed only from the top of the stack. You can retrieve取出, insert, or remove an element from the top of the stack. 在Java集合架构中,栈类Stack是作为Vector类的扩展实现的。An instance of Map图的实例 represents a group of objects, each of which is associated with a key键值. You can get the object from a map using a key键值, and you have to use a key to put the object into the map. Map接口建立元素和键值的一个映射关系,一个图中不能有重复的键值,每个键值对应一个值。键值就像下标,键值可以是任意类型的对象,整数、小数。The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integer. In Map, the keys can be any objects.实现Map接口的具体类:散列图HashMap、链式散列图LinkedHashMap、树形图TreeMap。The Collections class contains various static methods .Collections 类包括许多静态方法for operating on collections and maps, 管理集合与图for creating synchronized collection classes, 创建同步集合类for creating read-only collection classes.创建只读集合类Collections 类中的大多数方法都是用来处理线性表的。The Arrays class contains various static methods for sorting and searching arrays, for comparing arrays, and for filling array elements. It also contains a method for converting an array to a list. Array类中包含对数组进行排序、查找、比较和填充元素的各种静态方法,它还包含了将数组转换为线性表的方法。一般类型的使用希望一个集合中只有一种类型: HashSet set = new HashSet();只能向规则集中添加字符串, set.add(Red);从一个只有一种指定元素类型的集合中取值时,不需要进行类型转换。ArrayList list = new ArrayList();list.add(5.5); / 5.5 is automatically converted to new Double(5.5)list.add(3.0); / 3.0 is automatically converted to new Double(3.0)Double doubleObject = list.get(0); / No casting is neededdouble d = list.get(1); / Automatically converted to doubleimport java.util.*;public class TestHashSet public static void main(String args) Set set = new HashSet(); set.add(London); set.add(Paris); set.add(New York); set.add(San Francisco); set.add(Beijing); set.add(New York); System.out.println(set); Iterator iterator = set.iterator();迭代探子 while (iterator.hasNext() System.out.print(iterator.next() + -); System.out.println(); for (Object element: set) System.out.print(element.toString() + ); 第24章 多线程 Multithreading多个线程在多处理器上运行多个线程在单处理器上运行Multiple threads sharing a single CPU进程是资源调度和管理的最小单位This.n 成员变量this() 引用本类的构造方法super.n 子类引用父类的变量Super()引用父类的构造方法Program: Create and run three threads:创建并运行三个线程:The first thread prints the letter a 100 times. 第一个线程打印字母 a 100 次. The second thread prints the letter b 100 times.第二个线程打印字母 b 100 次.The third thread prints the integers 1 through 100. 第三个线程打印1-100的整数. 1、扩展Thread类来编写线程2、 通过实现Runnable接口来编写线程类The Static yield() MethodYou can use the yield() method to temporarily release time for other threads. For example, suppose you modify the code in Lines 57-58 in TestRunnable.java as follows:public void run() for (int i = 1; i = lastNum; i+) System.out.print( + i); Thread.yield();/每次打印一个数字后,线程printer100就会暂停。 Every time a number is printed, the print100 thread is yielded. So, the numbers are printed after the characters.The Static sleep(milliseconds) Method方法sleep(long mills)将线程置为休眠,休眠时间为指定的毫秒数。 例如修改 Example 24.1中的TestRunnable.java :public void run() for (int i = 1; i = 50) Thread.sleep(1);/每打印一个大于等于50的数字后,线程print100休眠1毫秒。 catch (InterruptedException ex) join() 方法可以使用 join() 方法强迫一个线程等待另一个线程结束。例如修改 Example 24.1中的TestRunnable.java :public void run() Thread thread4 = new Thead(new PrintChar(c,40); thread4.start();try for (int i = 1; i = lastNum; i+) System.out.print( + i); if (i = 50) thread4.join();/只有当线程thread4完成后,才会打印50-100的数。 catch (InterruptedException ex) wait() :强迫线程等待,直到调用wait方法的对象调用notify或notifyAll方法。Notify():该方法唤醒等待该对象的线程之一。notifyAll() :唤醒等待该对象的所有线程。The wait(), notify(), and notifyAll()方法 wait(), notify(), and notifyAll() 定义在Object类中,也可以用于促进活动线程之间的通信。线程的状态Thread States线程有五种状态:新建、就绪、运行、阻塞或结束。New, Ready, Running, Blocked, or Finished.isAlive(), interrupt(), and isInterrupted()isAlive() :判断线程状态的方法。如果线程处于就绪、阻塞、运行状态,返回true;如果线程处于新建并且没有启动的状态,或者已经结束,则返回false。?interrupt() :线程处于就绪状态或运行状态时,给它设置一个中断标识;当线程处于阻塞状态时,它会被唤醒并进入就绪状态。The interrupt() method interrupts a thread in the following way: If a thread is currently in the Ready or Running state, its interrupted flag is set; if a thread is currently blocked阻塞, it is awakened and enters the Ready state, and an java.io.InterruptedException is thrown.isInterrupted():是否被中断。The isInterrupt() method tests whether the thread is interrupted.线程的优先级可以设置优先级 setPriority(int priority). Priorities are number ranging 1 to 10优先级常量:Thread.MIN_PRIORITY represent 1Thread.MAX_PRIORITY represent 10Thread.NORM_PRIORITY represent 5 默认优先级default prioritythread3.setPrioritiy(Thread.MAX_PRIORITY);这样,thread3就会最先执行完毕,the thread for the print100 task will finished first.The deprecated stop(), suspend(), and resume() MethodsNOTE: The Thread class also contains the stop(), suspend(), and resume() methods. As of Java 2, these methods are deprecated (or outdated) because they are known to be inherently unsafe. You should assign null to a Thread variable to indicate that it is stopped rather than use the stop() method.Thread Pools线程池线程池是管理开发执行很多任务的理想方法。A thread pool is ideal to manage the number of tasks executing concurrently. JDK 1.5 uses the Executor interface for executing tasks in a thread pool and the ExecutorService interface for managing and controlling tasks. ExecutorService is a subinterface of Executor. JDK 1.5 使用 Executor 接口在线程池中执行任务, ExecutorService 接口用来管理和控制任务。 ExecutorService 是 Executor的子接口. To create an Executor object, use the static methods in the Executors class. 为了创建 Executor 对象, 使用 Executors 的静态方法. 同步与协作Thread SynchronizationA shared resource may be corrupted if it is accessed simultaneously by multiple threads. For example, two unsynchronized threads accessing the same bank account may cause conflict.如果一个共享资源被多个线程同时访问,可能会遭到破坏。Example: Showing Resource Conflict演示资源冲突Objective: Write a program that demonstrates the problem of resource conflict. Suppose that you create and launch one hundred threads, each of which adds a penny to an account. Assume that the account is initially empty. 假设创建并启动100个线程,每个线程都往同一个账户中加1。假设开始时账户是空的。import java.util.concurrent.*;public class AccountWithoutSync private static Account account = new Account(); public static void main(String args) ExecutorService executor = Executors.newCachedThreadPool(); / Create and launch 100 threads for (int i = 0; i 100; i+) executor.execute(new AddAPennyThread(); executor.shutdown(); / Wait until all tasks are finished while (!executor.isTerminated() System.out.println(What is balance ? + account.getBalance(); / A thread for adding a penny to the account private static class AddAPennyThread implements Runnable public void run() account.deposit(1); / An inner class for account private static class Account private int balance = 0; public int getBalance() return balance; public synchronized void deposit(int amount) int newBalance = balance + amount; / This delay is deliberately added to magnify the / data-corruption problem and make it easy to see. try Thread.sleep(1); catch (InterruptedException ex) balance = newBalance; synchronized 关键字The synchronized keyword 线程同步To avoid resource conflicts, Java uses the To avoid race conditions, more than one thread must be prevented from simultaneously entering certain part of the program, known as critical region. The critical region in the Listing 24.7 is the entire deposit method. You can use the synchronized keyword to synchronize the method so that only one thread can access the method at a time. There are several ways to correct the problem in Listing 24.7, one approach is to make Account thread-safe by adding the synchronized keyword in the deposit method in Line 45 as follows: 为避免资源冲突,应该防止多个线程同时进入程序的某一特定部分,程序中这样的部分称为临界区。public synchronized void deposit(double amount)Synchronizing Instance Methods and Static Methods关键词Lock 加锁 解锁是unlock当执行方法中某一个代码块时,同步语句不仅仅可以用于获准给对象加锁,而且可以用于要求对任何对象加锁。synchronized (expr) statements;执行同步语句时,如果要锁定的对象已经被另一个线程锁定,则在解锁之前,运行同步语句的线程将被阻塞。 任何同步方法都可以转化为同步语句: public synchronized void xMethod() / method body等价于下列语句:This method is equivalent topublic void xMethod() synchronized (this) / method body 利用加锁同步JDK 1.5 可以显示地使用锁。锁可以使用 newCondition() 方法创建 任意数目的 Condition 对象, 用来进行线程通信。ReentrantLock是为创建相互排斥的锁的Lock的具体实现。可以使用特定的公平策略创建锁。A synchronized instance method implicitly acquires a lock on the instance before it executes the method. JDK 1.5 enables you to use locks explicitly明确的. The new locking features are flexible and give you more control for coordinating threads. A lock is an instance of the Lock interface, which declares the methods for acquiring and releasing locks, as shown in Figure 24.14. A lock may also use the newCondition() method to create any number of Condition objects, which can be used for thread communications.Cooperation Among Threads 线程之间的协作方法 await(), signal(), and signalAll() 定义在Object类中,也可以用于促进活动线程之间的通信。await()、wait() :强迫线程等待,直到调用wait方法的对象调用notify或notifyAll方法。signal()、Notify():该方法唤醒等待该对象的线程之一。signalAll()、notifyAll() :唤醒等待该对象的所有线程。Deadlock 死锁有时两个或多个线程需要锁定几个共享对象。这时可能引起死锁,也就是说,每个线程已经锁定了一个对象,正等待锁定另一个对象。使用资源排序技术来避免死锁。Deadlock can be easily avoided by using a simple technique known as resource ordering.With this technique, you assign an order on all the objects whose locks must be acquired and ensure that each thread acquires the locks in that order. 进程条JProgressBar 通常是通过使用一个线程监视其他线程的完成状态来实现。minimum, value, maximum为什么要加锁?A synchronized method acquires a lock before it executes. In the case of an instance method, the lock is on the object for which the method was invoked. In the case of a static method, the lock is on the class. If one thread invokes a synchronized instance method (respectively, static method) on an object, the lock of that object (respectively, class) is acquired first, then the method is executed, and finally the lock is released. Another thread invoking the same method of that object (respectively, class) is blocked until the lock is released. Chapter 25 Networking第25章 网络基于套接字的通信面向连接传输通信方式客户机/服务器计算模式Client/Server Communications服务器端创建ServerSocket客户端书本P819创建一个服务器套接字(套接字socket表示为(IP地址:端口号),一个TCP连接被两个套接字唯一的确定),并把它附加到一个端口上,服务器从端口监听连接。客户启动时,服务器必须正在运行。服务器等候客户的连接请求一旦建立连接,客户和服务器就可以通过套接字进行通信客户执行下列语句请求与服务器进行连接。InputStream input = socket.getInputStream();OutputStream output = socket.getOutputStream();A Client/Server ExampleProblem: Write a client to send data to a server. The server receives the data, uses it to produce a result, and then sends the result back to the client. The client displays the result on the console. In this example, the data sent from the client is the radius of a circle, and the result produced bythe server is the area of the circle. Problem: 客户发送的数据室圆的半径,服务器生成的结果是圆的面积。注意:先启动服务器,再启动客户Serverimport java.io.*;import .*;import java.util.*;import java.awt.*;import javax.swing.*;public class Server extends JFrameprivate JTextArea jta = new JTextArea();Socket socket;DataInputStream inputFromClient;DataOutputStream outputToClient;public Server() setLayout(new BorderLayout(); add(new JScrollPane(jta), BorderLayout.CENTER); setTitle(Server); setSize(500, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); / It is necessary to show the frame here!tryServerSocket serverSocket = new ServerSocket(8000);jta.append(Server started at + new Date()+n);socket = serverSocket.accept();inputFromClient = new DataInputStream( socket.getInputStream();outputToClient = new DataOutputStream( socket.getOutputStream();while(true)double radius = inputFromClient.readDouble(); / Compute area double area = radius * radius * Math.PI; / Send area back to the client outputToClient.writeDouble(area); jta.append(Radius received from client: + radius + n); jta.append(Area found: + area + n);c
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 商铺租赁保险责任合同协议2025
- 融资合同2025年还款计划调整协议
- 平面设计合同协议2025
- 旅游合同续签补充协议2025版
- 2025年考勤异常处理与纪律处分考试试题及答案
- 国际体育赛事合同范本
- 地板质量保修合同范本
- 场地牛场租赁合同范本
- 土方外运合同补充协议
- 国资办委托管理协议书
- 建筑业十项新技术
- 鱼蛋白饲料生产线项目分析方案
- 二层小楼拆除施工方案
- 2025年4月自考03346项目管理试题
- 跨国公司外汇资金集中运营管理业务方案
- 基于BIM的莆田第25中教学楼项目招标造价管理
- 中国农业银行笔试题库(含答案)
- 基于单元视角解读教学设计 选择性必修一 植物生命活动的调节 环境因素参与调节植物的生命活动
- 血液净化中心规章制度
- 高考报名社会实践(10篇)
- 家政服务职业技能家庭照护员理论知识考核试题及答案
评论
0/150
提交评论