📄 runnabledemo.java
字号:
/*
* RunnableDemo.java
*
* Created on 2005年4月10日, 下午7:02
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
*
* @author Liu Bin
* @version
*/
public class RunnableDemo extends MIDlet implements CommandListener {
//Display管理
Display display = null;
Form form = new Form("通过Runnable创建线程");
Command cmdExit = new Command("退出", Command.STOP, 1);
Command cmdRun = new Command("运行", Command.ITEM, 2);
Command cmdStop = new Command("停止", Command.ITEM, 2);
MyThreaad p1, p2, p3;
public RunnableDemo() {
form.addCommand(cmdExit);
form.addCommand(cmdRun);
form.setCommandListener(this);
}
public void startApp() {
display = Display.getDisplay(this); //获得当前MIDlet的Display对象
display.setCurrent(form); //设置form对象为当前显示对象
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
/**
* 处理命令按钮事件
*/
public void commandAction(Command cmd, Displayable d) {
if (cmd == cmdExit) {
destroyApp(true);
} else if (cmd == cmdRun) {
//创建线程1
p1 = new MyThreaad(1);
//执行线程1
new Thread(p1).start();
//创建线程2
p2 = new MyThreaad(2);
//执行线程2
new Thread(p2).start();
//创建线程3
p3 = new MyThreaad(3);
//执行线程3
new Thread(p3).start();
form.removeCommand(cmdRun);
form.addCommand(cmdStop);
} else if (cmd == cmdStop) {
form.removeCommand(cmdStop);
form.addCommand(cmdRun);
p1.stopFlag = true;
p2.stopFlag = true;
p3.stopFlag = true;
}
}
/**
* 实现Runnable接口
*/
class MyThreaad implements Runnable {
//当前线程的ID标识
long id;
public boolean stopFlag;
MyThreaad(long id) {
this.id = id;
}
public void run() {
stopFlag = false;
long i=0;
System.out.println("线程"+ id + "开始执行完毕\n");
while (!stopFlag) {
System.out.println("当前线程"+id + " : " + i++);
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
System.out.println("线程"+ id + "执行完毕\n");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -