⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 nonsyncdemo.java

📁 《J2ME图形应用基础》第二章
💻 JAVA
字号:
/*
 * SyncDemo.java
 *
 * Created on 2005年4月11日, 下午12:12
 */

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 *
 * @author  Liu Bin
 * @version
 */
public class NonSyncDemo extends MIDlet implements CommandListener {
    //Display管理
    Display display = null;
    Form form = new Form("非线程同步演示");
    
    Command cmdExit = new Command("退出", Command.STOP, 1);
    Command cmdRun = new Command("运行", Command.ITEM, 2);
    Command cmdStop = new Command("停止", Command.ITEM, 2);
    
    //共享变量
    int sharedCounter = 0;
    
    MyThreaad p1, p2, p3;
    
    public NonSyncDemo() {
        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(this, 1);
            //执行线程1
            p1.start();
            
            //创建线程2
            p2 = new MyThreaad(this, 2);
            //执行线程2
            p2.start();
            
            //创建线程3
            p3 = new MyThreaad(this, 3);
            //执行线程3
            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;
        }
    }
    
    
    /**
     * 从Thread继承创建线程
     */
    class MyThreaad extends Thread {
        //当前线程的ID标识
        long id;
        NonSyncDemo instance;
        public boolean stopFlag;
        
        MyThreaad(NonSyncDemo father, long id) {
            instance = father;
            this.id = id;
        }
        
        public void run() {
            stopFlag = false;
            System.out.println("线程"+ id + "开始执行\n");
            while (!stopFlag) {
                System.out.println("线程"+id + ",优先级" +
                        this.getPriority() + "   当前值: " +
                        instance.sharedCounter++);
                System.out.println("线程"+id + ",优先级" +
                        this.getPriority() + "   新值: " +
                        instance.sharedCounter);
            }
            System.out.println("线程"+ id + "执行完毕\n");
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -