j2me中线程的使用

来源:互联网 发布:淘宝要怎么开 编辑:程序博客网 时间:2024/05/17 05:12

下面这个例子是上课时讲的,看完就基本明白线程的使用了 

import javax.microedition.lcdui.Canvas;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;
 
/**
 * @author Rock
 */
public class ThreadDemo extends MIDlet implements CommandListener {
    //Display管理
 
    Display display = null;
    Form form = null;
    Command cmdExit = null;
    Command cmdRun = null;
    Command cmdStop = null;
    MyThreaad p1, p2, p3;
    Canvas canvas =null;
 
    public ThreadDemo() {
        form = new Form("通过Thread创建线程");
        cmdExit = new Command("退出", Command.STOP, 1);
        cmdRun = new Command("运行", Command.ITEM, 2);
        cmdStop = new Command("停止", Command.ITEM, 2);
        form.addCommand(cmdExit);
        form.setCommandListener(this);
        display = Display.getDisplay(this);
 
//        canvas = new ();
    }
 
    public void startApp() {
        display.setCurrent(form);
    }
 
    public void pauseApp() {
    }
 
    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }
 
    public void commandAction(Command cmd, Displayable d) {
       // throw new UnsupportedOperationException("Not supported yet.");
        if (cmd == cmdExit) {
            destroyApp(true);
        }else if (cmd == cmdRun) {
           //创建线程1
            p1 = new MyThreaad(1);
            //执行线程1
            p1.start();
 
            //创建线程2
            p2 = new MyThreaad(2);
            //执行线程2
            p2.start();
 
            //创建线程3
            p3 = new MyThreaad(3);
            //执行线程3
            p3.start();
 
            form.removeCommand(cmdRun);
            form.addCommand(cmdStop);
        }
    }
 
    class MyThreaad extends Thread {
        //当前线程的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 + ",优先级"
                        + this.getPriority() + " : " + i++);
                try {
                    sleep(100);
                } catch (Exception e) {
                }
            }
            System.out.println("线程" + id + "执行完毕/n");
        }
    }
}
原创粉丝点击