如何中止线程
点击一个菜单项执行一个线程(我的是一个不断画图的程序)
然后点击另一个菜单项要做到移掉在画图的面板
加载进另一面板,可是我发现那个面板虽然已经移掉了,可在run()方法内使用输出函数还是发现线程在执行),请问怎样在点击另一个菜单项的瞬间关闭那个线程呢?
部分代码如下:
if (mouseEvent.canDrawMovedPath) {
float d = 20f;
float r = d / 2;
float sx = (float) lineStartX;
float sy = (float) lineStartY;
float tx = (float) lineCurrentX;
float ty = (float) lineCurrentY;
comp2D.setColor(Color.red);
comp2D.draw(new Line2D.Float(sx, sy, tx, ty));
comp2D.setColor(Color.green);
comp2D.draw(new Line2D.Float(tx - r - 5, ty, tx + r + 5, ty));
comp2D.draw(new Line2D.Float(tx, ty - r - 5, tx, ty + r + 5));
comp2D.draw(
new Arc2D.Float(tx - r, ty - r, d, d, 25, 40, Arc2D.OPEN));
comp2D.draw(
new Arc2D.Float(tx - r, ty - r, d, d, 115, 40, Arc2D.OPEN));
comp2D.draw(
new Arc2D.Float(tx - r, ty - r, d, d, 205, 40, Arc2D.OPEN));
comp2D.draw(
new Arc2D.Float(tx - r, ty - r, d, d, 295, 40, Arc2D.OPEN));
}
}
public void runThread() {
showTitle("--Wall Agent(no tight spaces) is running.");
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void stopThread() {
showTitle("--Wall Agent(no tight spaces) is stoped.");
if (runner != null) {
runner = null;
}
}
public void run() {
Thread thisThread = Thread.currentThread();
while (runner == thisThread) {
agent.moveOneStep();
repaint();
agent.pause(300);
}
}