首页 文章 精选 留言 我的

精选列表

搜索[官方镜像],共10000篇文章
优秀的个人博客,低调大师

提前曝光:【阿里Java技术进阶】官方钉群2月至3月直播排期预告!

作为【阿里Java技术进阶】钉钉群的管理员,小编我拿到了一手2月至3月份的直播排期,看到本篇文章的你有福了~如果你在本群的话我敢肯定你会准时来看直播!如果你不在本群的话,我敢打赌你读完本篇文章会立即扫码入群,快看看本次我们都邀请谁来直播了!!! 讲师:徐雷(阿里特邀专家)社区昵称:徐雷frank(点击昵称可关注讲师) 讲师介绍: 资深架构师,MongoDB中文社区联席主席,吉林大学计算机学士,上海交通大学硕士。从事了 10年+开发工作,专注于分布式架构,Java Spring Boot、Spring Cloud、MongoDB、Redis。 喜欢专研技术问题,擅长讲课,《MongoDB实战》第2版、《24种云计算架构设计模式》译者,2018年5月受邀成为《阿里巴巴Java和MongoDB技术认证》讲师,2018年8月与阿里巴巴资深专家P9

优秀的个人博客,低调大师

【JAVA集合框架一 】java集合框架官方介绍 Collections Framework Overview 集合框架总览 翻译 jav...

原文链接: https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html 原文内容也一并附加在本文最后. 简介: Java平台包含一个集合框架。 集合是表示一组对象的对象(如经典的Vector类)。 集合框架是用于表示和操作集合的统一体系结构,使集合可以独立于实现细节而被操纵。 集合框架的主要有点在于: 通过提供数据结构和算法减少编程工作量,因此您不必亲自编写它们。 通过提供数据结构和算法的高性能实现来提高性能。由于每个接口的各种实现都是可以互换的,因此可以通过切换实现来调整程序。 通过建立通用语言来回传递集合,提供不相关的API之间的互操作性。--可以部分理解为向上转型 多态 通过学习多个特定的集合API来减少学习API所需的工作量。 --通过自顶而下的API设计风格 不要求您实现特定的集合API来减少设计和实现API所需的工作量。--通过提供抽象类提供了很多默认实现 通过为集合和算法提供标准接口来操纵它们,从而促进软件重用。 集合框架包括: 集合接口。表示不同类型的集合,例如Set,List和Map。这些接口构成了框架的基础。 通用实现。集合接口的主要实现。 遗留实现。早期版本Vector和Hashtable中的集合类进行了改进,以实现集合接口。 特殊用途的实现。设计用于特殊情况的实现。这些实现展示非标准的性能特征,使用限制或行为。 并发实现。为高并发使用而设计的实现。 包装实现。将功能(如同步)添加到其他实现。 更简化便利的实现. 集合接口的高性能低复杂实现. 抽象实现。集合接口的部分实现,以促进自定义实现。 算法。collections中非常有用的静态方法,比如例如排序列表。 基础架构。为集合即可欧提供重要支持的接口。--就是一些其他辅助的,比如Iterable 数组工具类。基本类型和引用对象数组的实用函数。严格来说,并不是集合框架的一部分,这个特性与集合框架同时添加到Java平台,并依赖于相同的基础结构。 集合接口: 集合接口分为两大阵营,最基础的接口java.util.Collection,有下面这些后代: java.util.Setjava.util.SortedSetjava.util.NavigableSetjava.util.Queuejava.util.concurrent.BlockingQueuejava.util.concurrent.TransferQueuejava.util.Dequejava.util.concurrent.BlockingDeque 另外的一些集合接口派生于 java.util.Map 不过他们并是真正的集合。 但是,这些接口包含集合视角的操作,这些操作可以将它们作为集合进行操作。Map有以下后代: java.util.SortedMapjava.util.NavigableMapjava.util.concurrent.ConcurrentMapjava.util.concurrent.ConcurrentNavigableMap 集合中的许多修改方法是可选的. 也就是允许实现类并不必须要实现一个或者多个这种操作. 如果你尝试使用,将会抛出运行时异常UnsupportedOperationException 每个实现的文档必须指定支持哪些可选操作。 引入了几个术语来帮助本规范: 不支持修改操作的集合(如添加,删除和清除)称为不可修改,非不可修改的集合是可修改的。; 如果集合额外保证集合对象中没有任何可见的修改那么称之为为不可变,非不可变的就是可变的; 保证集合大小不变的的集合,即使元素可以变化更改,称之为固定大小,非固定大小的列表称之为可变大小; 支持快速(通常是固定时间)索引元素访问的List是随机访问(RandomAccess) List,比如arrayList,不支持快速索引访问的称之为顺序访问 (sequential access)List ,RandomAccess标记接口指明一个list具有支持随机访问的特性,这一点保证了你可以编写通用的算法代码,通过选择不同的随机访问还是顺序访问List,以达到更好的性能. 一些实现可以做到限制哪些元素(或者在Map场景下的键和值)可以被存储。可能的限制包括要求元素: 特定类型 不能为null 遵从一些自定的断言判断式(Obey some arbitrary predicate) 如果尝试往有限制的接口实现中添加不符合的元素,会出现运行时异常,比如 ClassCastException, IllegalArgumentException, or a NullPointerException. 如果尝试在有限制的实现中移除一个不符合条件的元素或者测试是否存在,会导致异常 不过一些受限制的集合支持这种用法. 集合实现: 集合的实现类一般遵从这样子的形式 < 实现特性>加上<接口名称>的形式 下表中列出了通用实现 通用实现类支持集合框架中所有的可选操作,并且对于元素没有任何的限制 他们都是非同步的 不过Collections类中包含了很多静态的工厂方法-synchronization wrappers同步包装器 可以在很多非同的集合中提供同步的功能. 所有新的实现都具有快速失败迭代器,它可以检测到非法的并发修改,并且快速而干净地(而不是报错异常)失败。 ps: fail-fast java集合框架中的一种机制,检测并发修改 AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList 和 AbstractMap 为了减少实现接口所需代价,提供了核心集合框架的基本实现。 这些类的API文档准确描述了每种方法的实现方式, 因此实现者知道哪些方法必须被重写,考虑到具体实现类的基本操作的性能。 并发集合: 应用程序中使用多个线程的集合的必须仔细编程,这个一般叫做并发编程 Java平台包含对并发编程的广泛支持。有关详细信息,请参阅Java Concurrency Utilities。 由于集合经常被使用,各种支持并发编程的接口和集合的实现都被包含在这些API中 这些类型,超出了前面提到过的同步包装,提供了并发编程中经常需要用到的特性 并发接口 BlockingQueueTransferQueueBlockingDequeConcurrentMapConcurrentNavigableMap 并发实现类 LinkedBlockingQueueArrayBlockingQueuePriorityBlockingQueueDelayQueueSynchronousQueueLinkedBlockingDequeLinkedTransferQueueCopyOnWriteArrayListCopyOnWriteArraySetConcurrentSkipListSetConcurrentHashMapConcurrentSkipListMap 设计目标: 主要的设计目标是编写一个体积小概念强大的API 新功能与当前程序差别不大,这一点非常重要.而且,需要在现有的基础上增加 而不是替代他们。 而且,新的API必须足够强大,才能够提供前面所述的所有优势。 为了使核心接口的数量保持较小, 接口不会尝试捕捉诸如易变性,可修改性和可调节性之类的细微区别 相反,在核心接口中一些调用是可选的 使得实现类可以抛出一个UnsupportedOperationException异常指示出他们不支持指定的可选操作 集合实现者必须清楚地在文档中表明实现支持哪些可选操作。 为了使每个核心接口中的方法数量保持较小, 只有在以下情况下,接口才包含方法: 这是一项真正的基本操作:就其他方面可以被合理定义而言, 它是一个基本的操作, 有一个不可抗拒的性能因素导致重要的实现类将会想要去重写它 所有关于集合的表现形式的互操作性至关重要。 这包括数组,在不改变语言的情况下,不能直接实现Collection接口。 因此, 该框架包含的方法可以将集合移入数组,将数组视为集合,将Map视为集合。 原文内容: Skip to Content Collections Framework Overview Introduction The Java platform includes acollections framework. Acollectionis an object that represents a group of objects (such as the classicVectorclass). A collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details. The primary advantages of a collections framework are that it: Reduces programming effortby providing data structures and algorithms so you don't have to write them yourself. Increases performanceby providing high-performance implementations of data structures and algorithms. Because the various implementations of each interface are interchangeable, programs can be tuned by switching implementations. Provides interoperability between unrelated APIsby establishing a common language to pass collections back and forth. Reduces the effort required to learn APIsby requiring you to learn multiple ad hoc collection APIs. Reduces the effort required to design and implement APIsby not requiring you to produce ad hoc collections APIs. Fosters software reuseby providing a standard interface for collections and algorithms with which to manipulate them. The collections framework consists of: Collection interfaces. Represent different types of collections, such as sets, lists, and maps. These interfaces form the basis of the framework. General-purpose implementations. Primary implementations of the collection interfaces. Legacy implementations. The collection classes from earlier releases,VectorandHashtable, were retrofitted to implement the collection interfaces. Special-purpose implementations. Implementations designed for use in special situations. These implementations display nonstandard performance characteristics, usage restrictions, or behavior. Concurrent implementations. Implementations designed for highly concurrent use. Wrapper implementations. Add functionality, such as synchronization, to other implementations. Convenience implementations. High-performance "mini-implementations" of the collection interfaces. Abstract implementations. Partial implementations of the collection interfaces to facilitate custom implementations. Algorithms. Static methods that perform useful functions on collections, such as sorting a list. Infrastructure. Interfaces that provide essential support for the collection interfaces. Array Utilities. Utility functions for arrays of primitive types and reference objects. Not, strictly speaking, a part of the collections framework, this feature was added to the Java platform at the same time as the collections framework and relies on some of the same infrastructure. Collection Interfaces Thecollection interfacesare divided into two groups. The most basic interface,java.util.Collection, has the following descendants: java.util.Set java.util.SortedSet java.util.NavigableSet java.util.Queue java.util.concurrent.BlockingQueue java.util.concurrent.TransferQueue java.util.Deque java.util.concurrent.BlockingDeque The other collection interfaces are based onjava.util.Mapand are not true collections. However, these interfaces containcollection-viewoperations, which enable them to be manipulated as collections.Maphas the following offspring: java.util.SortedMap java.util.NavigableMap java.util.concurrent.ConcurrentMap java.util.concurrent.ConcurrentNavigableMap Many of the modification methods in the collection interfaces are labeledoptional. Implementations are permitted to not perform one or more of these operations, throwing a runtime exception (UnsupportedOperationException) if they are attempted. The documentation for each implementation must specify which optional operations are supported. Several terms are introduced to aid in this specification: Collections that do not support modification operations (such asadd,removeandclear) are referred to asunmodifiable. Collections that are not unmodifiable aremodifiable. Collections that additionally guarantee that no change in theCollectionobject will be visible are referred to asimmutable. Collections that are not immutable aremutable. Lists that guarantee that their size remains constant even though the elements can change are referred to asfixed-size. Lists that are not fixed-size are referred to asvariable-size. Lists that support fast (generally constant time) indexed element access are known asrandom accesslists. Lists that do not support fast indexed element access are known assequential accesslists. TheRandomAccessmarker interface enables lists to advertise the fact that they support random access. This enables generic algorithms to change their behavior to provide good performance when applied to either random or sequential access lists. Some implementations restrict what elements (or in the case ofMaps, keys and values) can be stored. Possible restrictions include requiring elements to: Be of a particular type. Be not null. Obey some arbitrary predicate. Attempting to add an element that violates an implementation's restrictions results in a runtime exception, typically aClassCastException, anIllegalArgumentException, or aNullPointerException. Attempting to remove or test for the presence of an element that violates an implementation's restrictions can result in an exception. Some restricted collections permit this usage. Collection Implementations Classes that implement the collection interfaces typically have names in the form of <Implementation-style><Interface>. The general purpose implementations are summarized in the following table: The general-purpose implementations support all of theoptional operationsin the collection interfaces and have no restrictions on the elements they may contain. They are unsynchronized, but theCollectionsclass contains static factories calledsynchronization wrappersthat can be used to add synchronization to many unsynchronized collections. All of the new implementations havefail-fast iterators, which detect invalid concurrent modification, and fail quickly and cleanly (rather than behaving erratically). TheAbstractCollection,AbstractSet,AbstractList,AbstractSequentialListandAbstractMapclasses provide basic implementations of the core collection interfaces, to minimize the effort required to implement them. The API documentation for these classes describes precisely how each method is implemented so the implementer knows which methods must be overridden, given the performance of the basic operations of a specific implementation. Concurrent Collections Applications that use collections from more than one thread must be carefully programmed. In general, this is known asconcurrent programming. The Java platform includes extensive support for concurrent programming. SeeJava Concurrency Utilitiesfor details. Collections are so frequently used that various concurrent friendly interfaces and implementations of collections are included in the APIs. These types go beyond the synchronization wrappers discussed previously to provide features that are frequently needed in concurrent programming. These concurrent-aware interfaces are available: BlockingQueue TransferQueue BlockingDeque ConcurrentMap ConcurrentNavigableMap The following concurrent-aware implementation classes are available. See the API documentation for the correct usage of these implementations. LinkedBlockingQueue ArrayBlockingQueue PriorityBlockingQueue DelayQueue SynchronousQueue LinkedBlockingDeque LinkedTransferQueue CopyOnWriteArrayList CopyOnWriteArraySet ConcurrentSkipListSet ConcurrentHashMap ConcurrentSkipListMap Design Goals The main design goal was to produce an API that was small in size and, more importantly, in "conceptual weight." It was critical that the new functionality not seem too different to current Java programmers; it had to augment current facilities, rather than replace them. At the same time, the new API had to be powerful enough to provide all the advantages described previously. To keep the number of core interfaces small, the interfaces do not attempt to capture such subtle distinctions as mutability, modifiability, and resizability. Instead, certain calls in the core interfaces areoptional, enabling implementations to throw anUnsupportedOperationExceptionto indicate that they do not support a specified optional operation. Collection implementers must clearly document which optional operations are supported by an implementation. To keep the number of methods in each core interface small, an interface contains a method only if either: It is a trulyfundamental operation: a basic operations in terms of which others could be reasonably defined, There is a compelling performance reason why an important implementation would want to override it. It was critical that all reasonable representations of collections interoperate well. This included arrays, which cannot be made to implement theCollectioninterface directly without changing the language. Thus, the framework includes methods to enable collections to be moved into arrays, arrays to be viewed as collections, and maps to be viewed as collections. Copyright ©1993, 2018, Oracle and/or its affiliates. All rights reserved. Contact Us

优秀的个人博客,低调大师

Android官方开发文档Training系列课程中文版:Activity测试之创建单元测试

原文地址:http://android.xsoftlab.net/training/activity-testing/activity-unit-testing.html Activity单元测试除了可以快速的验证Activity的状态之外,还可以验证Activity与底层组件之间的交互。单元测试通常用于测试较小的代码单元(它们通常不依赖系统或者网络资源),它们可能是一个方法,一个类或者其它组件。例如,开发者可以通过单元测试来检查Activity是否含有正确的布局,或者是否触发了正确的Intent。 不过单元测试通常不适用于测试与系统有交互的UI组件,该类测试情况应当使用ActivityInstrumentationTestCase2。 这节课将会学习如何使用单元测试来验证用于启动Activity的Intent。因为测试运行于独立的环境之中,所以Intent并不会实际发送到Android系统,但是你可以检测该Intent所携带的数据是否正确。 创建用于Activity单元测试的测试用例 类ActivityUnitTestCase对单个的Activity测试提供了支持。要进行Activity的单元测试,需继承ActivityUnitTestCase。 在ActivityUnitTestCase中的Activity并不会由Android系统自动启动。如果要在这里启动Activity,必须在这里显式的调用startActivity()方法,并传入要执行的Intent。 例如: public class LaunchActivityTest extends ActivityUnitTestCase<LaunchActivity> { ... @Override protected void setUp() throws Exception { super.setUp(); mLaunchIntent = new Intent(getInstrumentation() .getTargetContext(), LaunchActivity.class); startActivity(mLaunchIntent, null, null); final Button launchNextButton = (Button) getActivity() .findViewById(R.id.launch_next_activity_button); } } 验证另一个Activity的启动 单元测试可能含有以下目的: 验证在Button按下后LaunchActivity是否启动了Intent. 验证被启动的Intent所包含的数据是否正确. 为了验证在Button按下后是否有Intent被触发,开发者可以使用getStartedActivityIntent()方法获得被触发的Intent。然后通过断言方法来验证该方法返回的Intent是否为null,以及该Intent所含的数据是否正确。如果两个断言方法都正确,那么可以断定成功了触发了该Intent。 开发者所实现的代码可能如下: @MediumTest public void testNextActivityWasLaunchedWithIntent() { startActivity(mLaunchIntent, null, null); final Button launchNextButton = (Button) getActivity() .findViewById(R.id.launch_next_activity_button); launchNextButton.performClick(); final Intent launchIntent = getStartedActivityIntent(); assertNotNull("Intent was null", launchIntent); assertTrue(isFinishCalled()); final String payload = launchIntent.getStringExtra(NextActivity.EXTRAS_PAYLOAD_KEY); assertEquals("Payload is empty", LaunchActivity.STRING_PAYLOAD, payload); } 因为LaunchActivity是独立运行的,所以不能够使用库TouchUtils来直接控制UI。为了可以模拟Button的点击时间,可以直接调用performClick()方法。

优秀的个人博客,低调大师

Android官方开发文档Training系列课程中文版:线程执行操作之线程间通讯

原文地址:http://android.xsoftlab.net/training/multiple-threads/communicate-ui.html 上节课我们学习了如何启动一项由ThreadPoolExecutor所管理的线程任务。最后这节课我们将学习如何从任务中发送结果数据给UI线程。这项手段可以使任务在执行完毕后将结果显示到UI中去。 每个APP拥有独立的UI线程。只有在UI线程中创建的对象才可以访问该线程中的其它对象。正因为运行任务的线程不是UI线程,所以它们不可以直接访问UI对象。为了将数据从后台线程转移到UI线程,需要使用运行在UI线程中的Handler对象。 在UI线程中定义Handler Handler是Android系统框架管理线程的一部分。Handler对象专门用于接收消息处理消息。 一般来说,可以为新线程创建一个Handler,也可以为一个已经连接好的线程创建Handler。当你将Handler连接到UI线程时,处理消息的代码都会运行在UI线程中。 在构建线程池的类的构造方法中实例化一个Handler对象,并将该对象的引用存储于全局变量中。通过Handler(Looper)重载构造方法所实例化Handler可以与UI线程产生关联。这个构造方法所使用的Looper参数是Android系统的线程管理框架的另一部分。当以指定的Looper实例初始化一个Handler对象时,Handler对象会运行在Looper对象所在的线程中。 private PhotoManager() { ... // Defines a Handler object that's attached to the UI thread mHandler = new Handler(Looper.getMainLooper()) { ... 在Handler内,重写handleMessage()方法。Android系统会在Handler所管理的线程中接收到一条新的消息时回调该方法: /* * handleMessage() defines the operations to perform when * the Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; ... } ... } } 将数据从非UI线程转移到UI线程 为了将数据从后台进程转移到UI进程,首先将数据的引用以及UI对象存储于任务对象中。接下来,将该任务对象及状态码传给由Handler对象所初始化的对象。在这个对象内,发送一条包含状态码的任务对象给Handler。因为Handler是运行在UI线程的,所以它可以将数据交给UI对象。 存储数据于任务对象中 举个例子,这里有一个Runnable对象,运行于后台线程,它用于解码一个Bitmap对象,并将其存储于它所属的对象PhotoTask中。该Runnable还会存储一个状态码:DECODE_STATE_COMPLETED。 // A class that decodes photo files into Bitmaps class PhotoDecodeRunnable implements Runnable { ... PhotoDecodeRunnable(PhotoTask downloadTask) { mPhotoTask = downloadTask; } ... // Gets the downloaded byte array byte[] imageBuffer = mPhotoTask.getByteBuffer(); ... // Runs the code for this task public void run() { ... // Tries to decode the image buffer returnBitmap = BitmapFactory.decodeByteArray( imageBuffer, 0, imageBuffer.length, bitmapOptions ); ... // Sets the ImageView Bitmap mPhotoTask.setImage(returnBitmap); // Reports a status of "completed" mPhotoTask.handleDecodeState(DECODE_STATE_COMPLETED); ... } ... } ... PhotoTask还包含了一个用于展示Bitmap的ImageView的句柄。尽管引用Bitmap以及ImageView的是同一个对象,但是还是不能将Bitmap赋值给ImageView,因为当前并没有处在UI线程中。 发送状态到对象层级 PhotoTask在层级内处于第二高度。它维护了图像的解码数据以及一个View对象。它会接收PhotoDecodeRunnable中的状态码,并将其传给维护线程池以及Handler的那个对象。 public class PhotoTask { ... // Gets a handle to the object that creates the thread pools sPhotoManager = PhotoManager.getInstance(); ... public void handleDecodeState(int state) { int outState; // Converts the decode state to the overall state. switch(state) { case PhotoDecodeRunnable.DECODE_STATE_COMPLETED: outState = PhotoManager.TASK_COMPLETE; break; ... } ... // Calls the generalized state method handleState(outState); } ... // Passes the state to PhotoManager void handleState(int state) { /* * Passes a handle to this task and the * current state to the class that created * the thread pools */ sPhotoManager.handleState(this, state); } ... } 将数据展示到UI PhotoManager收到从PhotoTask中发来的状态码,然后处理这个PhotoTask对象。因为状态是TASK_COMPLETE,所以先创建一个Message,然后通过这个Message对象将状态以及人物对象发送给Handler: public class PhotoManager { ... // Handle status messages from tasks public void handleState(PhotoTask photoTask, int state) { switch (state) { ... // The task finished downloading and decoding the image case TASK_COMPLETE: /* * Creates a message for the Handler * with the state and the task object */ Message completeMessage = mHandler.obtainMessage(state, photoTask); completeMessage.sendToTarget(); break; ... } ... } 最后,在Handler.handleMessage()中检查每条消息的状态。如果消息的状态为TASK_COMPLETE,那么表明该任务已经终结,那么Message中所包含的PhotoTask对象包含了一个Bitmap以及一个ImageView。因为Handler.handleMessage()是运行在UI线程的,所以它可以安全的将Bitmap赋给ImageView: private PhotoManager() { ... mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message inputMessage) { // Gets the task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Gets the ImageView for this task PhotoView localView = photoTask.getPhotoView(); ... switch (inputMessage.what) { ... // The decoding is done case TASK_COMPLETE: /* * Moves the Bitmap from the task * to the View */ localView.setImageBitmap(photoTask.getImage()); break; ... default: /* * Pass along other messages from the UI */ super.handleMessage(inputMessage); } ... } ... } ... } ... }

优秀的个人博客,低调大师

Android官方开发文档Training系列课程中文版:线程执行操作之线程池操作

原文地址:http://android.xsoftlab.net/training/multiple-threads/run-code.html#StopThread 上节课我们学习了如何定义一个类用于管理线程以及任务。这节课将会学习如何在线程池中运行任务。要做到这一点,只需要往线程池的工作队列中添加任务即可。当一条线程处于闲置状态时,那么ThreadPoolExecutor会从任务队列中取出一条任务并放入该线程中运行。 这节课还介绍了如何停止一个正在运行中的任务。如果在任务开始后,可能发现这项任务并不是必须的,那么就需要用到任务取消的功能了。这样可以避免浪费处理器的时间。举个例子,如果你正从网络上下载一张图像,如果侦测到这张图像已经在缓存中了,那么这时就需要停止这项网络任务了。 在线程池中的线程内运行任务 为了在指定的线程池中启动一项线程任务,需要将Runnable对象传给ThreadPoolExecutor的execute()方法。这个方法会将任务添加到线程池的工作队列中去。当其中一个线程变为闲置状态时,那么线程池管理器会从队列中取出一个已经等待了很久的任务,然后放到这个线程中运行: public class PhotoManager { public void handleState(PhotoTask photoTask, int state) { switch (state) { // The task finished downloading the image case DOWNLOAD_COMPLETE: // Decodes the image mDecodeThreadPool.execute( photoTask.getPhotoDecodeRunnable()); ... } ... } ... } 当ThreadPoolExecutor启动一个Runnable时,它会自动调用Runnable的run()方法。 中断执行中的代码 如果要停止一项任务,那么需要中断该任务所在的线程。为了可以预先做到这一点,那么需要在任务创建时存储该任务所在线程的句柄: class PhotoDecodeRunnable implements Runnable { // Defines the code to run for this task public void run() { /* * Stores the current Thread in the * object that contains PhotoDecodeRunnable */ mPhotoTask.setImageDecodeThread(Thread.currentThread()); ... } ... } 我们可以调用Thread.interrupt()方法来中断一个线程。这里要注意Thread对象是由系统控制的,系统会在应用进程的范围之外修改它们。正因为这个原因,在中断线程之前,需要对线程的访问加锁。通常需要将这部分代码放入同步代码块中: public class PhotoManager { public static void cancelAll() { /* * Creates an array of Runnables that's the same size as the * thread pool work queue */ Runnable[] runnableArray = new Runnable[mDecodeWorkQueue.size()]; // Populates the array with the Runnables in the queue mDecodeWorkQueue.toArray(runnableArray); // Stores the array length in order to iterate over the array int len = runnableArray.length; /* * Iterates over the array of Runnables and interrupts each one's Thread. */ synchronized (sInstance) { // Iterates over the array of tasks for (int runnableIndex = 0; runnableIndex < len; runnableIndex++) { // Gets the current thread Thread thread = runnableArray[taskArrayIndex].mThread; // if the Thread exists, post an interrupt to it if (null != thread) { thread.interrupt(); } } } } ... } 在多数情况下,Thread.interrupt()会使线程立刻停止。然而,它只会将那些正在等待的线程停下来,它并不会中止CPU或网络任务。为了避免使系统变慢或卡顿,你应当在开始任意一项操作之前测试是否有中断请求: /* * Before continuing, checks to see that the Thread hasn't * been interrupted */ if (Thread.interrupted()) { return; } ... // Decodes a byte array into a Bitmap (CPU-intensive) BitmapFactory.decodeByteArray( imageBuffer, 0, imageBuffer.length, bitmapOptions); ...

优秀的个人博客,低调大师

Android官方开发文档Training系列课程中文版:布局性能优化之ListView的优化

原文地址:http://android.xsoftlab.net/training/improving-layouts/smooth-scrolling.html 想要让ListView滑动流畅的关键所在是减轻主线程的负担。要确保任何的磁盘访问、网络访问、或者SQL访问都是在单独的线程中执行的。如果要测试APP的状态,可以开启StrictMode。 使用后台线程 使用工作线程可以使UI线程将所有的注意力都集中在UI的绘制上。在很多情况下,使用AsyncTask所提供的功能就可以在工作线程中处理耗时任务。AsyncTask会自动的将execute()发起的请求排队,并依次执行。这意味着你不要自己创建线程池。 在下面的示例代码中,AsyncTask被用来加载一张图像,并在加载结束后自动的将其渲染到UI上。它还在图像加载时展示了一个旋转的进度条。 // Using an AsyncTask to load the slow images in a background thread new AsyncTask<ViewHolder, Void, Bitmap>() { private ViewHolder v; @Override protected Bitmap doInBackground(ViewHolder... params) { v = params[0]; return mFakeImageLoader.getImage(); } @Override protected void onPostExecute(Bitmap result) { super.onPostExecute(result); if (v.position == position) { // If this item hasn't been recycled already, hide the // progress and set and show the image v.progress.setVisibility(View.GONE); v.icon.setVisibility(View.VISIBLE); v.icon.setImageBitmap(result); } } }.execute(holder); 从Android 3.0开始,AsyncTask提供了一项新特性:可以将任务运行在多核处理器上。你可以使用executeOnExecutor()方法发起执行请求,这样多个请求就可以同时进行,同时进行的任务数量取决于CPU的核心数量。 使用View Holder持有View对象 在滑动ListView时,代码可能会频繁的调用findViewById(),这会降低性能。就算是Adapter将已经加载过的View返回,但是在复用时还是需要去查询这些View来更新它们。杜绝重复使用findViewById()的方法就是使用”View Holder”设计模式。 ViewHolder对象将每个View组件存储于布局容器的tag属性内,所以你可以快速访问它们而不需要每次都去查询。首先,你需要创建一个类来持有已加载的View: static class ViewHolder { TextView text; TextView timestamp; ImageView icon; ProgressBar progress; int position; } 然后对ViewHolder的成员属性赋值,然后将其存放在布局容器内: ViewHolder holder = new ViewHolder(); holder.icon = (ImageView) convertView.findViewById(R.id.listitem_image); holder.text = (TextView) convertView.findViewById(R.id.listitem_text); holder.timestamp = (TextView) convertView.findViewById(R.id.listitem_timestamp); holder.progress = (ProgressBar) convertView.findViewById(R.id.progress_spinner); convertView.setTag(holder); 那么现在就可以很方便的对这些View组件进行访问,而不再需要对它们单独进行查询,如此便可以节省出宝贵的CPU资源。

优秀的个人博客,低调大师

Android官方开发文档Training系列课程中文版:布局性能优化之布局层级优化

原文地址:http://android.xsoftlab.net/training/improving-layouts/index.html 引言 布局是直接影响用户体验的关键部分。如果实现的不好,那么布局很有可能会导致内存的紧张。Android的SDK包含的一些工具可以用来检查布局性能上的问题。结合本章的课程学习,你将有能力以低成本的内存开销实现更为顺畅的UI体验。 优化布局层级 有一个常见的误解就是使用基本的布局结构会使布局更高效。然而却不是这样的,每一个控件、布局容器都需要执行初始化、排布、绘制等过程。举个例子,使用内嵌的LinearLayout会使布局层级过度加深。进一步讲,内嵌多个使用了layout_weight参数的控件所花费的代价尤其高昂,因为每个子View都需要被测量两次。这在布局被重复加载时尤为重要,比如使用在ListView或GridView中的时候。 在这节课我们将会学习如何使用Hierarchy Viewer工具及Layoutopt工具来检查、优化布局。 布局检查 Android的SDK包含了一个名为Hierarchy Viewer的工具。使用该工具可以帮助发现影响布局性能的瓶颈。 Hierarchy Viewer工作于所选择的进程上,它会显示一个布局树。每个View节点上的信号灯代表了该View在测量、排布、绘制上的性能优劣,这可以帮助你发现潜在的问题。 举个例子说明:下图是ListView的一个Item。该Item左边用于显示图片,而右边则显示两行文本。因为该Item会被进行多次加载,所以对其优化的话,那么UI性能会有显著的提升。 Hierarchy Viewer工具位于< sdk>/tools/目录下。打开后,Hierarchy Viewer会列出当前的可用设备以及设备上运行的组件。点击Load View Hierarchy来浏览所选组件的布局层级。下图是上图位于ListView中的运行效果演示: 在上图中,我们可以看到View的层级为3,并且在文本的排布上发现了一些问题。点击每个节点我们可以看到每个阶段所花费的时间(如下图所示)。那么我们就可以很清晰的知道哪个Item在测量、排布、渲染上花费的时间最长,所以我们就需要花点时间专门对其优化。 这里我们可以看到每个阶段所花费的时间: Measure: 0.977ms Layout: 0.167ms Draw: 2.717ms 调整布局 因为上面的示例说布局的性能慢是由于内嵌了一个LinearLayout,所以改进这部分性能只能通过扁平化来处理。要尽量使布局变浅变宽,杜绝变窄变深。RelativeLayout可以实现这样的布局。所以当使用RelativeLayout实现这样的布局时,那么可以看到布局的层级变为了2。我们所看到的布局图就是这个样子: 下面是优化后的时间开销: Measure: 0.598ms Layout: 0.110ms Draw: 2.146ms 我们可能会看到很微小的改进。 在改进时间上的大部分差别是由于LinearLayout的权重造成的,它会降低测量的速度。这里的示例仅仅是个优化手段的演示,在开发过程中应当认真考虑是否有必要使用权重。 使用Lint 开发者应该使用lint工具来检查布局层级是否有可优化的地方。Lint 与Layoutopt 相比有更加强大的功能。一些Lint的检查规则如下: 使用组合图形 - 一个包含了ImageView和TextView的LinearLayout作为组合图形处理起来更加高效。 合并根帧布局 - 如果一个FrameLayout是根布局,并且它没有提供背景色或内边距什么的,那么可以使用合并标签将其替换,这可以稍微的改进性能。 无用的叶子节点 - 如果一个布局没有子View,没有背景色,那么通常可以将其移除。 无用的中间节点 - 如果一个布局内部只含有一个子View,并且不是ScrollView或者根布局,也没有背景色,那么可以将它移除,并将其子View移动到它的父容器内。 非常深的布局嵌套 - 一个被嵌套很深的布局通常不利于性能。考虑使用RelativeLayout或者GridLayout这种扁平化布局来改进性能。默认的最大深度为10。 Lint的另一个好处就是它被集成进了Android Studio。Lint会在程序编译时自动运行。 你也可以管理检查Lint的配置,在Android Studio内通过File>Settings>Project Settings路径可以找到。 Lint可以自动的修复一些问题,并且会对余下的问题提供一些优化建议,以便使开发者手动修复。

优秀的个人博客,低调大师

Android官方开发文档Training系列课程中文版:后台服务之IntentService的使用

原文地址:http://android.xsoftlab.net/training/run-background-service/send-request.html 上节课我们学习了如何创建IntentService。这节课我们主要学习如何通过Intent使IntentService执行工作请求。Intent可以将任何数据交给IntentService处理。你可以在Activity或者Fragment的任意方法内发送Intent给IntentService。 创建并发送工作请求到IntentService 为了创建一个工作请求并将其发送给IntentService,首先我们需要创建一个显式 的Intent对象,然后向其添加请求数据,最后再通过startService()将它发送到IntentService。 下面的代码演示了这个过程: 为名RSSPullService的IntentService创建一个显式 的Intent。 /* * Creates a new Intent to start the RSSPullService * IntentService. Passes a URI in the * Intent's "data" field. */ mServiceIntent = new Intent(getActivity(), RSSPullService.class); mServiceIntent.setData(Uri.parse(dataUrl)); 调用startService()。 // Starts the IntentService getActivity().startService(mServiceIntent); 注意,你可以在Activity或者Fragment的任何地方发送工作请求。举个例子,如果你需要先获得用户的输入数据,那么就可以将工作请求的发送代码放在Button按钮的点击回调内。 一旦调用了startService(),那么IntentService将会在onHandleIntent()方法内执行工作请求,并且它会在任务完成后自动停止。 下一个步骤就是如何将工作的完成结果反馈给请求调用处。下一节课将会学习如何使用BroadcastReceiver完成这个过程。

优秀的个人博客,低调大师

Android官方开发文档Training系列课程中文版:后台服务之IntentService的创建

原文地址:http://android.xsoftlab.net/training/run-background-service/index.html 引言 除非特别指定,否则所有的操作都是在UI线程中执行的。不过这会引起问题,因为长时间的耗时操作会妨碍UI线程的运行。这会惹恼用户,并可能会引起系统错误。为了避免这样的情况出现,Android为此提供了一些类,可以使这些耗时操作放在单独的线程中执行。这里用到最多的就是IntentService了。 这节课主要学习如何实现IntentService,以及如何向它发送工作请求,以及如何响应它的执行结果。 创建后台服务 IntentService提供了一个非常简单的构造方法。IntentService允许执行耗时操作,而又不会引起UI线程的阻塞。同样的,IntentService还不受UI生命周期的影响。所以它可以在一个单独的环境中持续运行。 不过IntentService也是有限制的,列举如下: 它不可以与UI线程直接交互。为了将结果递送到UI,不得不采用广播的形式将结果发送出去。 工作请求是按顺序执行的。如果目前已经有一个操作在IntentService中执行,那么再往其中发送操作请求的话,这些操作请求都将会等待,直至第一个操作完成。 IntentService中的操作不可以被中断。 不管怎样,大多数情况下,IntentService是执行后台操作的首选方式。 这节课主要学习如何实现IntentService,以及如何创建请求回调方法onHandleIntent(),最后我们还会学习如何在清单文件中声明该IntentService。 创建IntentService 首先需要创建一个类并继承IntentService,然后重写它的onHandleIntent()方法: public class RSSPullService extends IntentService { @Override protected void onHandleIntent(Intent workIntent) { // Gets data from the incoming Intent String dataString = workIntent.getDataString(); ... // Do work here, based on the contents of dataString ... } } 这里要注意普通Service的那些回调方法,比如onStartCommand()方法,它会被IntentService自动调用,所以在IntentService内部最好不要重写这些方法。 在清单文件中声明IntentService IntentService同样需要在清单文件中定义。它的定义方式与普通Service是一样的。 <application android:icon="@drawable/icon" android:label="@string/app_name"> ... <!-- Because android:exported is set to "false", the service is only available to this app. --> <service android:name=".RSSPullService" android:exported="false"/> ... <application/> 其中android:name属性说明了IntentService的类名。 这里要注意:Service标签内并没有包含Intent Filter。因为其它组件是通过显示Intent发送工作请求的。所以这里不需要定义Intent Filter。这也意味着只有相关组件内的APP或者拥有相同用户ID的程序才可以访问该服务。 现在我们已经定义好了一个IntentService类,接下来就可以通过Intent对象向其发送工作请求了。关于如何构建相关对象以及如何发送请求到IntentService的相关内容将会在下节课学习。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。