java线程停止问题

dzry24 2009-11-18 01:42:02



/**
* 停止线程
*/
public class StopThread {
/** 线程对象 */
private ThreadA thread = new ThreadA();
/** 自定义线程类 */
class ThreadA extends Thread{
//用一个boolean值标记线程是否需要运行。
private boolean running = false;
//覆盖了父类的start方法,
public void start(){
//将running置为ture,表示线程需要运行
this.running = true;
super.start();
}
public void run(){
System.out.println("ThreadA begin!");
int i=0;
try {
//如果running为真,说明线程还可以继续运行
while (running){
System.out.println("ThreadA: " + i++);
//sleep方法将当前线程休眠。
Thread.sleep(200);
}
} catch (InterruptedException e) {
}

System.out.println("ThreadA end!");
}
public void setRunning(boolean running){
this.running = running;
}
}
/**
* 启动ThreadA线程
*/
public void startThreadA(){
System.out.println("To start ThreadA!");
thread.start();
}
/**
* 停止ThreadA线程
*/
public void stopThreadA(){
System.out.println("To stop ThreadA!");
thread.setRunning(false);
}

public static void main(String[] args) {
StopThread test = new StopThread();
//启动ThreadA线程
test.startThreadA();
//当前线程休眠一秒钟
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//停止ThreadA线程
test.stopThreadA();
}
}

while(runing)不是个死循环了吗??
...全文
99 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiguabaihe 2009-11-18
  • 打赏
  • 举报
回复
我先不管该程序能不能运行,你的程序有两个线程,一个主线程,一个是threadA线程。而cpu是以时间片的形式分别运行这俩个线程的。如果cpu只让threadA线程占用的话你的while(running)就是一个死循环,可是当主线程获得cpu时它就会执行test.stopThreadA(); 这条语句,将你的running的值改为FALSE,所以就没有表现出死循环的效果
很久以前飞 2009-11-18
  • 打赏
  • 举报
回复
这程序能运行吗?
感觉不行 strat();
和 run(); 方法都有 能用thread.strat(); 吗?
pasband 2009-11-18
  • 打赏
  • 举报
回复
public void stopThreadA(){
System.out.println("To stop ThreadA!");
thread.setRunning(false);
}

这里将running置为false了,线程的循环就结束了,线程也就退出了
plplum 2009-11-18
  • 打赏
  • 举报
回复
while(runing)只要你不调用线程的stop方法,它就会一直运行。
你的程序中test.stopThreadA(); 使线程停止运行了。

62,615

社区成员

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

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