扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
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 处理星空的更新并重绘任务,使得整个星空不断得往屏幕下方“延伸”。这样就生成了一个简单的星空移动的效果。
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。