- 浏览: 809774 次
- 性别:
- 来自: 广州
最新评论
-
mixture:
语句int num1, num2;的频度为1;语句i=0;的频 ...
算法时间复杂度的计算 [整理] -
zxjlwt:
学习了。http://surenpi.com
[问题解决]Error: ShouldNotReachHere() [整理] -
Animal:
谢谢 楼主 好东西
算法时间复杂度的计算 [整理] -
univasity:
gaidandan 写道缓存失败,,模拟器上可以缓存,同样代码 ...
[开发总结]WebView使用中遇到的一些问题&解决 -
blucelee2:
那么麻烦干吗,而且这种方法会导致,当拉太小的时候样式会丢掉,整 ...
[SWT]SashForm中固定单侧大小(&实现面板隐藏)
Using Threads in J2ME Applications
<!-- --><!-- --><!-- --><!-- --><!-- -->
<!-- -->
by Eric Giguere
February 2003
One of the defining features of the Java environment is its built-in support for threads . Threads let an application perform multiple activities simultaneously. When used properly, threads let the application's user interface remain responsive while it performs lengthy operations like network communication or very complicated computations. While user interface responsiveness is important no matter what the platform, it's even more so on the handheld and consumer-oriented devices that the J2ME platform targets. A basic understanding of how to use threads is key to writing effective J2ME applications, whether you're using the more limited facilities of the Connected Limited Device Configuration (CLDC) or the fuller features of the Connected Device Configuration (CDC). This article explains the concepts behind threads and how you can use them in your own applications. <!-- -->
What is a Thread? The Java Tutorial defines a thread as "a single sequential flow of control within a program." Threads are the fundamental units of program execution. Every running application has at least one thread. An application consisting of two or more threads is known as a multithreaded application.
Each thread has a context associated with it. The context holds information about the thread, such as the address of the currently executing instruction and storage for local variables. The context is updated as the thread executes. The context also stores the thread's state. A thread can be in any of the following states:
A thread that is running, ready, or suspended is a live thread. A terminated thread is also known as a dead thread.
Although an application may have many threads, the underlying device has a small, fixed number of processors (often just one or two) available for code execution. Threads share these processors by taking turns being in the running state. This arrangement is called thread scheduling .
Thread scheduling is a complicated affair over which the application has little control. The system (either the underlying operating system or the Java virtual machine, depending on how the threads are implemented) gives each ready thread a chance to run for a short time (the suspended threads are ignored), switching rapidly from one thread to another. This context switching can occur at any time. The only real influence the application has over thread scheduling is via the thread's priority level : higher-priority threads execute more often than those with lower priority. <!-- -->
The Thread Object Threads are dynamic in nature, existing only as part of a running application. The Java runtime associates each live thread with an instance of
J2ME provides two variants of the
Notice the lack of methods to stop or interrupt a running thread - more on this later. CDC's
Starting Threads To start a new thread you need two things: an instance of The <!-- --> You create a <!-- --> The system starts a new thread to invoke the
As it happens, the <!-- --> You start the thread by creating an instance of the subclass and invoking its <!-- --> Which way is preferable? Functionally, there is no real difference. If you can implement the
Furthermore, inheriting from
There are no restrictions on what a thread does in its <!-- --> Note that a thread has access to all the methods and fields of the <!-- --> If two threads simultaneously access the same data, thread synchronization (discussed later) becomes a concern. <!-- -->
Stopping Threads As I already mentioned, the
Once started, then, a J2ME thread lives until it intentionally or unintentionally (as a result of an uncaught exception) exits the
It's important to provide a way to stop an application's threads in short order. The simplest way is to have each thread periodically check a boolean variable: <!-- --> This works well when only one thread at a time executes a given <!-- --> It often makes sense to perform the check several times within the loop, before and after lengthy operations, and to break out of the loop immediately: <!-- --> Normally, you want a thread to exit as quickly as possible, delaying only enough to clean up after itself.
If a thread is using any kind of system resource - such as a network connection or a record store - that it created or opened itself, remember to use a <!-- --> Otherwise, the first thread that exits when an exception isn't caught may prevent other threads from accessing the resource. Using a
Once one thread has "asked" another thread to stop, the first thread can see whether the second is still alive by calling its <!-- --> Be careful, though: If you invoke
Thread Synchronization Starting and stopping threads is easy. The hard part is getting threads to interact safely. Because a context switch can occur at any time, the newly running thread can find itself reading data that a previously running thread was not done writing. Interacting threads must use thread synchronization to control who can read or write shared data at any given time.
Thread synchronization depends on a construct called a monitor . A monitor acts as a gatekeeper, ensuring that only one thread at a time has access to data. Whenever a thread needs to access protected data, it asks the monitor to lock the data for its own use. Other threads interested in the same data are forced to wait until the data is unlocked, at which point the monitor will lock the data for one of the waiting threads and allow it to proceed with its processing.
Any Java object can act as a monitor to control access to data using the <!-- --> If two threads call this method simultaneously, one is forced to wait until the other has left the synchronized block.
Because any Java object can act as a monitor, the <!-- --> Synchronizing with <!-- --> Static methods can be declared this way as well, even though there is no <!-- --> Instead, static methods use the class object of the class in which they are declared. The example above is equivalent to: <!-- --> Many of the core Java classes use synchronized methods. The <!-- --> Although
Thread synchronization works only when threads cooperate. To protect mutable data (data that can be changed) properly, all
threads accessing the data must access it through synchronized code blocks. If the data is encapsulated in a class, this is easily done by making all (or most) of the methods synchronized - but make sure you understand which monitor is being used to do the synchronization. For example, notice that a significant change occurs when you remove the synchronized block from <!-- --> This version of <!-- --> The first version precluded any other changes to the string buffer while a thread was executing
Of course, thread synchronization comes at a cost. Locking and unlocking data takes time, even on the fastest of processors. If your classes are immutable
- their external state does not change after initialization - then you can often dispense with synchronization. The
Thread synchronization does entail one danger: Two threads can deadlock if each attempts to lock data already locked by the other. Suppose thread A locks object X and thread B locks object Y, and then A attempts to lock Y at the same time B tries to lock X. Both threads block, and there's no way to unblock them. Deadlock avoidance is an important consideration when designing your application. A simple avoidance technique is to lock objects in the same order every time - always lock X before Y, for example. For more information about deadlock and deadlock avoidance, see the Resources section. <!-- -->
Waiting and Notifications Synchronization controls access to shared data, but often you want a thread to wait for an event to occur before accessing the data. A common solution is to have a thread read and process commands from a queue, commands placed there by other threads. If you use a <!-- --> This kind of loop is known as a busy wait , because the thread is always busy executing code. You want to avoid busy waits because they waste valuable processor cycles that other threads could be putting to good use. What you want is a suspended wait , where the thread is suspended until the desired event occurs. Suspended threads do not affect the scheduling of other threads.
As it happens, the monitors used for thread synchronization can also be used for thread suspension. If you think about it, thread synchronization is really just a special case of thread suspension, because each thread entering a synchronized block waits its turn for access to the data. The monitor maintains a queue of waiting threads, allowing only one thread at a time to enter the block.
Because every Java object can act as a monitor, the <!-- --> The thread must lock the object before invoking its
The
Once a thread suspends itself, another thread releases it by invoking the same object's <!-- --> Again, the second thread must lock the object before calling
Armed with this knowledge, you can rework the <!-- --> This is a much better behaved version, because the worker thread executes only when there are items in the queue.
As a rule, you should avoid suspending threads that your application did not create. System-defined threads - including those that deliver user-interface events and other notifications - are often shared among multiple applications. Suspending a system thread can affect the user interface, making the application appear to lock up. It may also prevent critical notifications from being delivered to other applications. Read the article Networking, User Experience, and Threads for more details. <!-- -->
A Real-Life Example I'll conclude this look at threads with a real-world example involving the Wireless Messaging API (WMA), a J2ME optional package that enables applications to send and receive Short Message Service (SMS) messages.
An application using the WMA can register to be notified whenever a message arrives for it. The WMA defines a <!-- --> The application creates an object that implements this interface and registers it with the WMA subsystem. When a message arrives for the application, the WMA subsystem invokes the <!-- --> The <!-- --> Notice how the <!-- --> Although this code fragment doesn't show it, the real advantage to the
An alternative implementation is to write a message receiver that creates a new thread to read and process each message as it arrives. Note that threads may be slow to create and individual devices may limit the number of threads that are active at any given time, so this technique may not be practical if many messages are to be received in a short timespan. <!-- -->
Resources The Threads and Multithreading section of Sun's Java Developer web site is also a good resource for more information, as are the following books:
<!-- --><!-- -->About the Author: Eric Giguere is a software developer for iAnywhere Solutions, a subsidiary of Sybase, where he works on Java technologies for handheld and wireless computing. He holds BMath and MMath degrees in Computer Science from the University of Waterloo and has written extensively on computing topics.
原文:http://developers.sun.com/mobility/midp/articles/threading2/ |
发表评论
-
对Java的I/O流理解
2011-02-19 23:04 1959这是很久前另一个BLOG上的,现在不用了。转过来吧,方便查看. ... -
A*寻路(J2ME实现)
2011-02-19 23:00 1278这是很久前另一个BLOG上的,现在不用了。转过来吧,方便查看. ... -
J2ME上检测是否支持特定的API
2011-02-19 22:59 1513这是很久前另一个BLOG上的,现在不用了。转过来吧,方便查看. ... -
J2me paint[转]
2011-02-19 22:58 1427这是很久前另一个BLOG上的,现在不用了。转过来吧,方便查看. ... -
[JSR-184][3D编程指南(译文)]第一部分:快速进入移动JAVA 3D编程世界
2011-01-23 00:37 1705[英文原文&源码下载] ... -
[JSR-184][3D编程指南]Part V: Heightmap terrain rendering using M3G
2011-01-22 23:13 1878<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]Part IV:M3G built-in collision,light physics and camera perspec
2011-01-22 23:04 2122<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]Part III: Particle systems and immediate mode rendering (2)
2011-01-22 22:56 1531<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]Part III: Particle systems and immediate mode rendering (1)
2011-01-22 22:48 2218<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]Part II: Light 3D theory and orientation
2011-01-22 22:29 1512<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]Part I: Quick jump into the world of Mobile Java 3D programming
2011-01-22 22:07 2313<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]目录索引
2011-01-22 21:25 1413Series of 3D programming tutori ... -
[Kuix][转]Kuix的事件处理机制
2009-10-08 18:19 1651原文连接 kuix这 ... -
[积累]getResourceAsStream()返回null的问题
2009-03-13 22:04 2645getResourceAsStream()可以获取JAR包内的 ... -
[资料]根据J2ME(MIDP)虚拟机对程序编写的优化方式
2009-02-27 09:39 14381、关于虚拟机 我认为 ... -
[资料]MIDP2.0中如何通过代码画半透明的圆和椭圆
2009-02-27 09:10 1600最近在做一个小Demo时,需要画一个半透明的圆,看遍M ... -
[资料]MIDP设计模式之集结贴[JavaME]
2009-02-23 22:07 13831: 架构性宣言: MI ... -
[资料]MVC在J2ME项目中的应用之MVC慨述
2009-02-23 21:48 1267内容提要: 本文简要的介绍了MVC模式的思想,并分析了M ... -
[资料]基于MVC模式的J2ME应用程序框架设计
2009-02-23 21:24 2848原文:http://www.mcu123.com/ ... -
[JSR-135][资料]渐进式下载
2009-02-22 16:17 1891Progressive download ...
相关推荐
7. **线程管理**:J2ME应用中的多任务处理通常需要自定义线程,以避免阻塞UI。源码会展示如何创建和管理`Thread`对象。 8. **错误处理和调试**:学习如何在Eclipse中设置断点、查看日志和调试J2ME应用,这对于问题...
不过,不同设备对优先级的支持可能不同,因此在实际应用中效果可能不一致。 四、线程池 虽然J2ME的标准库没有提供线程池功能,但开发者可以自行实现简单的线程池管理,通过复用已创建的线程来减少资源消耗。 五、...
在Java Micro Edition (J2ME)中,线程和网络编程是两个至关重要的概念,尤其对于开发移动设备上的应用程序来说。J2ME为资源有限的设备提供了轻量级的Java平台,因此理解和掌握这两个主题是编写高效、响应式以及能够...
在开发J2ME应用时,我们需要编写配置文件如`midlet.jad`和`midlet.jar`,它们分别用于描述应用程序的元数据和包含编译后的代码。 2. **开发环境与工具** 常用的J2ME开发工具有NetBeans、Eclipse和JCreator等,它们...
1. **KVM(Java Virtual Machine for Embedded Devices)**:J2ME应用程序运行在KVM上,这是一个专为小型设备优化的虚拟机,它不支持完整的Java Class库,而是采用CLDC(Connected Limited Device Configuration)和...
6. **J2ME应用发布** - **JAR (Java Archive)**:包含应用的类文件和资源文件。 - **jad (Java Application Descriptor)**:描述应用的元数据,如MIDlet(应用程序的主体)信息、版本、权限等。 7. **安全与限制*...
本文聚焦于线程池技术在J2ME网络通信中的应用,旨在通过优化多线程管理,提高网络通信效率,同时减少资源消耗。 #### J2ME网络通信中的多线程挑战 在J2ME环境下,网络通信通常需要在独立的线程中执行,以确保主线...
8. **Profiler和Performance Analysis**: 为了优化J2ME应用的性能,开发者可以使用像VisualVM这样的Java性能分析工具。它们提供内存使用、CPU消耗和线程状态的详细视图,帮助定位并修复性能瓶颈。 9. **文档和学习...
在NetBeans中,调试J2ME应用程序主要有两种方式:模拟器调试和实际设备调试。 1. **模拟器调试**:NetBeans集成了多个J2ME模拟器,如Sun Wireless Toolkit (SWT) 和Nokia Java SDK。在项目属性中配置所需的模拟器,...
本篇将围绕“J2ME应用实例源代码”这一主题,深入探讨J2ME的游戏开发实践,特别是通过“坦克大战”等经典游戏的源码解析,来阐述J2ME开发中的关键技术和设计思路。 1. **J2ME架构与环境搭建** J2ME由配置...
理解如何在J2ME中使用精灵对于创建动态、交互式的用户体验至关重要。 1. **精灵的概念**: - 精灵是一种二维图形对象,可以在游戏场景中独立移动和动画化。它们通常由多个帧组成,通过快速切换帧来创建连续的动作...
### 线程池技术在J2ME网络通信中的应用研究 #### 一、引言 随着嵌入式设备的迅速发展,特别是智能手机和平板电脑等手持移动设备的普及,...通过合理的实现和优化,线程池技术将成为J2ME应用开发中不可或缺的一部分。
7. **资源管理**:在“rec”文件夹中存放的图片资源是J2ME应用中常见的图形元素,它们可能被用来装饰用户界面或者在游戏中作为角色或背景。 8. **编译与打包**:J2ME应用的开发需要使用专用的J2ME集成开发环境(IDE...
完成开发后,J2ME应用通常通过OTA(Over-The-Air)方式分发,用户可以通过手机浏览器下载安装。此外,应用也可以预装在设备中或通过应用商店提供。 ### 总结 J2ME作为历史悠久且广泛应用于移动开发的平台,虽然...
这部分源码可能会展示如何在J2ME应用中实现数据持久化,包括查询、插入、更新和删除操作。 总的来说,这个压缩包提供了全面的J2ME无线应用开发实践案例,涵盖了从基础到高级的各种主题。对于想要深入学习J2ME的...
在J2ME中,数据存储通常使用Record Management System (RMS),它提供了一种存储和检索小数据集的方法。RMS中的RecordStore类可以看作是小型数据库,适合保存应用程序的状态和用户数据。 **应用发布与安装** MIDlet...
Socket编程在J2ME中的应用主要涉及到网络通信的基础知识,特别是Java Micro Edition (J2ME) 平台上的网络编程。J2ME是Java平台的一个子集,主要用于嵌入式设备和移动设备,如手机、PDA等。在这个场景下,Socket编程...
开发J2ME应用通常需要使用Java IDE,如Eclipse或NetBeans,它们都提供了J2ME项目模板和调试工具。模拟器是测试应用的重要工具,帮助开发者在没有实际设备的情况下预览和测试应用。 **4. GUI编程** J2ME使用MIDP的...
在J2ME中,多线程的使用可以实现游戏的流畅运行,例如,一个线程负责游戏的图形渲染,另一个线程则处理用户的输入事件,这样即使在复杂的交互中,游戏画面也不会出现卡顿。 对于新手开发者来说,了解并实践多线程是...
- Wireless Toolkit(WTK):Sun Microsystems提供的官方开发工具,包含模拟器,用于测试和调试J2ME应用程序。 - NetBeans或Eclipse:现代IDE,支持J2ME开发,提供了更友好的界面和集成的开发环境。 3. MIDP...