如何中止线程

alin19 2003-04-09 11:16:12
点击一个菜单项执行一个线程(我的是一个不断画图的程序)
然后点击另一个菜单项要做到移掉在画图的面板
加载进另一面板,可是我发现那个面板虽然已经移掉了,可在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);
}
}
...全文
42 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
alin19 2003-04-10
  • 打赏
  • 举报
回复
书上说这样会不安全,推荐我上面使用的方法
这个问题我在程序主框架里actionPerformed()里适当位置调用该面板的stopThread()方法就解决了
mercury1231 2003-04-10
  • 打赏
  • 举报
回复
线程结束一般用interrupt
旋转的魔方 2003-04-10
  • 打赏
  • 举报
回复
先程一般是不提倡强制中断的,
wyqiang 2003-04-10
  • 打赏
  • 举报
回复
线程结束一般用interrupt
徐蕴 2003-04-09
  • 打赏
  • 举报
回复
thread.interrupt()
gameboy999 2003-04-09
  • 打赏
  • 举报
回复
我使用的方式是设置一个static变量的方式。

毕竟terminate 线程好像不安全

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧