📄 waitnotifydemo.java
字号:
/*
* WaitNotifyDemo.java
*
* Created on 2005年4月11日, 下午4:38
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
*
* @author Liu Bin
* @version
*/
public class WaitNotifyDemo 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);
//共享变量
private int contents = 0;
private boolean available = false;
MyThreaad p1, p2;
public WaitNotifyDemo() {
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, false);
//执行线程1
p1.start();
//创建线程2
p2 = new MyThreaad(2, true);
//执行线程2
p2.start();
form.removeCommand(cmdRun);
form.addCommand(cmdStop);
} else if (cmd == cmdStop) {
form.removeCommand(cmdStop);
form.addCommand(cmdRun);
p1.stopFlag = true;
p2.stopFlag = true;
}
}
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("Gut Exception: " + e.toString());
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("Put Exception: " + e.toString());
}
}
contents = value;
available = true;
notifyAll();
}
/**
* 从Thread继承创建线程
*/
class MyThreaad extends Thread {
//当前线程的ID标识
long id;
boolean isRead;
public boolean stopFlag;
MyThreaad(long id, boolean isRead) {
this.isRead = isRead;
this.id = id;
}
public void run() {
stopFlag = false;
System.out.println("线程"+ id + "开始执行\n");
int i=0;
while (!stopFlag) {
if (isRead) {
put(++i);
System.out.println("线程"+id + ",设置值为:" + i);
} else {
System.out.println("线程"+id + ",读取值为:" + get());
}
}
System.out.println("线程"+ id + "执行完毕\n");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -