日期:2014-05-20  浏览次数:20845 次

求助关于线程控制的问题
运行没有问题 但是有一个BUG 当不停点击“ok”就会不停的启动新线程 也就不停的加快速度 怎么样修改这个程序呢?谢谢!
import   javax.microedition.lcdui.*;
import   javax.microedition.midlet.*;

public   class   GaugeTest   extends   MIDlet   implements   CommandListener
{
private   Display   display;
private   Form   f;
GaugeThread   gt;
public   GaugeTest()
{
display   =   Display.getDisplay(this);
}
public   void   startApp()
{
f   =   new   Form( "000000 ");
  gt   =   new   GaugeThread( "hahaha ",true,20,0);
new   Thread(gt).start();
f.append(gt);
f.get(0).setLayout(Item.LAYOUT_EXPAND);
f.addCommand(new   Command( "停止 ",Command.STOP,1));
f.addCommand(new   Command( "ok ",Command.OK,1));
f.setCommandListener(this);
display.setCurrent(f);
}
public   void   commandAction(Command   c,Displayable   d)
{
String   cmd   =   c.getLabel();
if   (cmd.equals( "停止 "))
{
gt.stop();
}
if   (cmd.equals( "ok "))
{
new   Thread(gt).start();
gt.start();
}
}
public   void   pauseApp()
{}
public   void   destroyApp(boolean   arg)
{}
}
class   GaugeThread   extends   Gauge   implements   Runnable
{
private   boolean   flag;
private   int   maxValue;

public   GaugeThread(String   lbl,boolean   b,int   maxValue,int   value)
{
super(lbl,b,maxValue,value);
this.maxValue   =   maxValue;
}
public   void   run()
{
while(!flag)
{
int   newValue   =   getValue()   +1;
if   (newValue   ==   maxValue)
{
newValue   =0;
}
setValue(newValue);
try   {
Thread.sleep(700);
}catch(Exception   ex){}
}
}
public   void   stop()
{
flag   =   true;
}
public   void   start()
{
flag   =   false;
}
}

------解决方案--------------------
第一个办法:让ok和stop互斥。点完ok以后,只能点stop,只有在stop的情况下,才能点ok
第二个办法:点ok的时候,现stop,然后再start。注意同步
------解决方案--------------------
理论上明了 能不能把代码贴上来?
------解决方案--------------------
逻辑错了

while条件的地方不能用flag,当flag为false的时候退出run()方法线程就死了.
另外就是lz线程开的太多太乱.
还有就继承runnable的class里不要定义start方法,会和Thread的start冲突.

帮你改了.

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

public class GaugeTest extends MIDlet implements CommandListener
{
private Display display;
private Form f;
GaugeThread gt;
private Thread thread = null;

public GaugeTest()
{
display = Display.getDisplay(this);
}
public void startApp()
{
f = new Form( "000000 ");
gt = new GaugeThread( "hahaha ",true,20,0);
thread = new Thread(gt);
thread.start();
f.append(gt);
f.get(0).setLayout(Item.LAYOUT_EXPAND);
f.addCommand(new Command( "停止 ",Command.STOP,1));
f.addCommand(new Command( "ok ",Command.OK,1));
f.setCommandListener(this);