- 浏览: 801398 次
- 性别:
- 来自: 广州
最新评论
-
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 1920这是很久前另一个BLOG上的,现在不用了。转过来吧,方便查看. ... -
A*寻路(J2ME实现)
2011-02-19 23:00 1241这是很久前另一个BLOG上的,现在不用了。转过来吧,方便查看. ... -
J2ME上检测是否支持特定的API
2011-02-19 22:59 1462这是很久前另一个BLOG上的,现在不用了。转过来吧,方便查看. ... -
J2me paint[转]
2011-02-19 22:58 1386这是很久前另一个BLOG上的,现在不用了。转过来吧,方便查看. ... -
[JSR-184][3D编程指南(译文)]第一部分:快速进入移动JAVA 3D编程世界
2011-01-23 00:37 1660[英文原文&源码下载] ... -
[JSR-184][3D编程指南]Part V: Heightmap terrain rendering using M3G
2011-01-22 23:13 1839<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]Part IV:M3G built-in collision,light physics and camera perspec
2011-01-22 23:04 2075<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]Part III: Particle systems and immediate mode rendering (2)
2011-01-22 22:56 1503<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]Part III: Particle systems and immediate mode rendering (1)
2011-01-22 22:48 2179<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]Part II: Light 3D theory and orientation
2011-01-22 22:29 1482<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]Part I: Quick jump into the world of Mobile Java 3D programming
2011-01-22 22:07 2270<!-- 整理收集自网络,收藏以便日后查阅 --> ... -
[JSR-184][3D编程指南]目录索引
2011-01-22 21:25 1370Series of 3D programming tutori ... -
[Kuix][转]Kuix的事件处理机制
2009-10-08 18:19 1622原文连接 kuix这 ... -
[积累]getResourceAsStream()返回null的问题
2009-03-13 22:04 2548getResourceAsStream()可以获取JAR包内的 ... -
[资料]根据J2ME(MIDP)虚拟机对程序编写的优化方式
2009-02-27 09:39 14041、关于虚拟机 我认为 ... -
[资料]MIDP2.0中如何通过代码画半透明的圆和椭圆
2009-02-27 09:10 1557最近在做一个小Demo时,需要画一个半透明的圆,看遍M ... -
[资料]MIDP设计模式之集结贴[JavaME]
2009-02-23 22:07 13161: 架构性宣言: MI ... -
[资料]MVC在J2ME项目中的应用之MVC慨述
2009-02-23 21:48 1241内容提要: 本文简要的介绍了MVC模式的思想,并分析了M ... -
[资料]基于MVC模式的J2ME应用程序框架设计
2009-02-23 21:24 2811原文:http://www.mcu123.com/ ... -
[JSR-135][资料]渐进式下载
2009-02-22 16:17 1860Progressive download ...
相关推荐
关于J2ME应用中一些多线程的使用方法和示例
J2Me中精灵,涂层,线程等知识结合的应用,让你更加熟悉j2Me背景图的绘制,事件的机制,线程的调用
音乐的控制,rms的操作类,java字符串解析 将字符串解析成字符数组,java进度条实例模板,j2me中将对象转换成字节数组的方法,j2me联网测试,j2me多线程的应用实例,j2me Socket通信例子 客户端,服务器端
本套资料工具非常适合在手机上学习、开发j2me应用。具体包括: 1.8本官方j2me编程类库参考,可以使用uc浏览器查看。 2.tengge手机端j2me教程,80多节,内含示例程序、做好的软件和效果图片。 3.手机端j2me编译...
本人编写的一个j2me游戏,其中有游戏精灵,双缓冲技术,线程的应用,碰撞检测等,其中处理了游戏声音!适合初学者!
每一个连接在服务器端都由一个单独的线程来管理,在线程中创建数据输入输出流,每个客户端发送的消息都在服务器端由管理这个客户端的线程完成转发。 ChatThread是一个线程类,构造方法的参数是Socket对象,构造方法...
本书详细讲解了J2ME的图形用户界面、游戏线程、记录存储、通用联网架构等基础知识,还在以往MIDP1.0的基础上增补了2.0的新内容,并对这些新技术加以详细介绍,这些技术包括高级用户界面的新组件、GameAPI游戏开发...
本文介绍了移动计算的特点, 根据目前无线网络和移动设备应用程序设计的局限性, 提出了基于J2ME+Agent 的多线程的移 动应用平台的设计方案, 并引入了中间件思想...平台在移动系统环境中具有较高的适应性和良好的使用性。
25J2ME代码优化 高级界面开发 02高级界面开发1:基本界面和Command 03高级界面开发2:Command事件和List 04高级界面开发3:TextBox,Ticker和Alert 05高级界面开发4:表单元素 06高级界面开发5:表单元素事件 07案例1 工具...
javaME 源码 包括基础知识 、Canvas、RMS 、...8多线程应用 9移动网络应用 10文件管理 11个人信息管理 12无线消息服务 13Push技术 14XMl应用 15多媒体开发 16游戏开发 17设计模式 18单元测试 19"在线听歌"商务应用实例
j2me功能实现的详细介绍和技术实现的完整代码 其中包含书中各章的源程序,分别在以下目录中: ch01 Java手机程序设计入门 ch02 J2ME核心类及...源程序的使用方法已在书中的附录的《常见问题解答中》进行了说明。
对J2ME的详细讲解,对大家都很有帮助哦。里面有各个控件的使用及线程的使用都有详细的描述。可以加深对手机开发的理解和应用。
Shane Conder ShaneConder拥有丰富的开发经验,在过去的10年中,他把主要精力集中在移动和嵌入式开发领域,迄今已设计并开发了基于Android、iPhone、BREW、Blackberry、J2ME、Palm和WindowsMobile的诸多商业软件。...
本书主要介绍如何用Java和C#编程语言开发手机应用程序以及在移动通信中的应用,包括:J2ME核心类及MIDlet类;基于Java开发MIDlet程序;图形处理及低级事件处理;多线程编程;即时消息传送;I/O及网络编程;数据库...
因此,针对它们的问题和移动设备计算能力弱和无线网络覆盖范围小,带宽很低而且连接不稳定的局限性,本文提出了基于J2ME和Agent的多线程的共用网移动应用平台的设计方案。 2 移动计算 移动计算...
java手机软件开发资料全集 资料清单: 1、Java手机程式设计入门 2、J2ME+手机+开发+视频 3、J2ME开发大全 4、Java(学习JAVA必备教程),看完了你也会编手机JAR软件了! 5、java_手机游戏开发入门教程 6、Java多...
的 Android SDK 提供了在 Android 平台上使用 JaVa 语言进行 Android 应用开发必须的工具和 API 接口。 特性 • 应用程序框架 支持组件的重用与替换 • Dalvik Dalvik Dalvik Dalvik 虚拟机 专为移动设备优化 • ...
实例6 在窗口中显示背景图 16 实例7 在窗体中绘制图形 18 实例8 利用JNI实现窗口特效 20 实例9 文件选择对话框 24 实例10 改变字体 26 实例11 应用JTree 28 实例12 应用JTable 30 实例13 记事本 32 实例14 使用...