java让线程空转_Java多线程-一个简单的线程,实现挂起和恢复的功能

public class MySprite implements Runnable {

/*

* 线程用变量

*/

private boolean running = false;

private boolean waiting = false;

private Thread thread;

/*

* Business 变量

*/

private String name;

public MySprite(String name) {

this.name = name;

this.thread = new Thread(this);

}

/**

* 启动线程

*/

public void start() {

running = true;

thread.start();

}

/**

* 挂起线程

*/

public void suspend() {

if (waiting) { // 是挂起状态则直接返回

return;

}

synchronized (this) {

this.waiting = true;

}

}

/**

* 恢复线程

*/

public void resume() {

if (!waiting) { // 没有挂起则直接返回

return;

}

synchronized (this) {

this.waiting = false;

this.notifyAll();

}

}

/**

* 停止线程

*/

public void stop() {

if (!running) { // 没有运行则直接返回

return;

}

synchronized (this) {

running = false;

}

}

public void run() {

for(;;) {

try {

// 线程挂起和退出处理

synchronized (this) {

if (!running) {

break;

}

if (waiting) {

this.wait();

}

}

// 应该做的事情

cry();

// 进入等待状态

Thread.sleep(50);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

private void cry() {

System.out.println(name + ":woo!");

}

}

之前也是实现了Runnable接口,得到线程 Thread worker = new Thread(this);

调用worker.wait();

提示报错:java.lang.IllegalMonitorStateException

产生错误原因可以查看:http://blog.csdn.net/intlgj/article/details/6245226

代码转摘自:http://www.cnblogs.com/hcfalan/archive/2008/06/16/1222960.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值