俄罗斯方块暂停java,月光软件站 - 编程文档 - Java - JavaDiamonds(俄罗斯方块) 中可暂停线程的实现...

这篇博客探讨了在Java中如何实现游戏线程的控制,包括线程的暂停、继续、中止和重启。通过`SuspensibleThread`类,实现了线程的生命周期管理,使用`volatile`关键字确保线程安全,并通过`wait()`和`notify()`进行同步。文章还强调了避免过度消耗CPU资源的重要性。
摘要由CSDN通过智能技术生成

下载地址

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;

}

}

down_info.asp?id=36434

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值