?? 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 + -