j2me线程同步
package prj9_1;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class MIDlet6 extends MIDlet {
protected void startApp() throws MIDletStateChangeException {
TicketThread tt = new TicketThread();
Thread th1 = new Thread(tt);
Thread th2 = new Thread(tt);
th1.start();
th2.start();
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
class TicketThread implements Runnable{
private int ticketNum = 10;
public void run(){
while(true){
synchronized(this){//synchronized(this)为函数加锁,当函数没有执行完,其它线程不能进入执行该函数,直到该函数被执行完
//就像给一个门加上锁,一个人拿钥匙进了门,另一个人要等到这个人出来交出钥匙才能进去
if(ticketNum==0){
System.out.println("没有票了");
break;
}
else{
try{
Thread.currentThread().sleep(1000);
}catch(Exception ex){}
ticketNum--;
System.out.println(Thread.currentThread().getName()+"卖出一张票,还剩下"+ticketNum+"张票");
}
}
}
}
}
}
转载请说明出处,本文来自:【前线玩】http://www.qxwan.com/thread-313-1-1.html
如需了解更多,可访问 http://www.qxwan.com
浙公网安备 33010602011771号