j2se 1.3 里有一项新的改进,那就是提供了一个可以更简单的实现多任务调度执行的定时器类,调度由一个后台线程完成。midp 同样也包含了这一改进,使得 j2me 开发人员从中受益。
j2me 提示了两个类用来定义和调试任务, 他们分别是 timertask 和 timer。timertask 是用户定义的需要被调度的所有任务的抽象基类。timer 类在任务执行的时候负责创建和管理执行线程。
要定义一个任务,定义一个 timertask 的子类,并实现 run 方法。例如
import java.util.*;public class mytask extends timertask{ public void run() { system.out.println( "running the task" ); }} |
import java.util.*;timer timer = new timer();timertask task = new mytask();// 在执行这个任务前等待十秒...timer.schedule( task, 10000 );// 在执行任务前等待十秒,然后每过十秒再执行一次timer.schedule( task, 5000, 10000 ); |
import javax.microedition.midlet.*;import javax.microedition.lcdui.*;import java.util.*;public class timerdemo extends midlet { display display; starfield field = new starfield(); fieldmover mover = new fieldmover(); timer timer = new timer(); public timerdemo() { display = display.getdisplay( this ); } protected void destroyapp( boolean unconditional ) { } protected void startapp() { display.setcurrent( field ); timer.schedule( mover, 100, 100 ); } protected void pauseapp() { } public void exit(){ timer.cancel(); // stop scrolling destroyapp( true ); notifydestroyed(); } class fieldmover extends timertask { public void run(){ field.scroll(); } } class starfield extends canvas { int height; int width; int[] stars; random generator = new random(); boolean painting = false; public starfield(){ height = getheight(); width = getwidth(); stars = new int[ height ]; for( int i = 0; i < height; ++i ){ stars[i] = -1; } } public void scroll() { if( painting ) return; for( int i = height-1; i > 0; --i ){ stars[i] = stars[i-1]; } stars[0] = ( generator.nextint() % ( 3 * width ) ) / 2; if( stars[0] >= width ){ stars[0] = -1; } repaint(); } protected void paint( graphics g ){ painting = true; g.setcolor( 0, 0, 0 ); g.fillrect( 0, 0, width, height ); g.setcolor( 255, 255, 255 ); for( int y = 0; y < height; ++y ){ int x = stars[y]; if( x == -1 ) continue; g.drawline( x, y, x, y ); } painting = false; } protected void keypressed( int keycode ){ exit(); } }} |
timerdemo midlet 使用了一个 timer 对象 timer 来调度执行一个 timertask 任务 fieldmover,时间间隙 100 毫秒。fieldmover 处理星空的更新并重绘任务,使得整个星空不断得往屏幕下方“延伸”。这样就生成了一个简单的星空移动的效果。
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器