JavaDiamonds(俄罗斯方块) 中可暂停线程的实现

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

下载地址

http://www.shengzhen.com.cn/javadiamonds/

游戏中的所有的正在下落的形状都从该类继承

package javablock.model;

public class SuspensibleThread

extends Thread {

private volatile boolean runing = true;

private volatile boolean pause = false;

public SuspensibleThread() {

}

//run方法不可再被继承了

final public void run() {

try {

while (runing) {

//当线程被暂停时 将会进入runing的循环检测中,

//这时有必要使用yield给于其他线程调用continueThread的机会

this.yield();

//如果没有sleep(10)此while循环会占用大量cpu时间

Thread.sleep(10);

while (!pause && runing) {

runTask();//注意runtask要实现线程安全

}

if (!pause && runing) {

//synchronized (this)是必须的

synchronized (this) {

this.wait();

}

}

if (!runing) {

break;

}

}

}

catch (InterruptedException ex) {

runing = false;

}

}

/**在继承runTask方法中应该有sleep方法

* */

public void runTask() throws InterruptedException {

Thread.sleep(1);

}

//暂停

public synchronized void pauseThread() {

pause = true;

}

//继续

public synchronized void continueThread() {

pause = false;

notify();

}

//中止线程

public synchronized void endThread() {

pause = true;

runing = false;

interrupt();

}

//重启线程

public synchronized void restart() {

runing = true;

pause = false;

this.start();

}

public boolean isThreadPause() {

return pause;

}

public boolean isThreadRunnig() {

return runing;

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航