后天我要参加我的exame演示,所以我需要在它之前做一些直截了当,我希望你们能帮助我。
首先我知道有4种状态的线程(即运行,就绪,阻塞,终止),但是我不太确定它在Java中是如何工作的。在我的代码中,我使用thread.sleep(3000)在程序中做一些等待,这是否使线程阻塞或准备好?
另外我注意到我可能没有以正确的方式使用线程,让我给你看一些代码
public class BattleHandler implements Runnable {
private Player player;
private Monster enemyMonster;
private Dungeon dungeon;
private JTextArea log;
private GameScreen gScreen;
public void run() {
try {
runBattle();
}
catch(Exception e) { System.out.println(e);}
}
public BattleHandler(Player AttackingPlayer, JTextArea log, GameScreen gScreen) {
this.player = AttackingPlayer;
this.log = log;
this.gScreen = gScreen;
}
public void setDungeon(Dungeon dungeon) {
this.dungeon = dungeon;
}
public Dungeon getDungeon() {
return dungeon;
}
public Monster getEnemyMonster() {
return enemyMonster;
}
public void setMonster() {
// First check if dungeon have been init, if not we can't generate the mob
if(dungeon != null) {
enemyMonster = new Monster();
// Generate monster stats
enemyMonster.generateStats(dungeon);
}else {
System.out.println("Dungeon was not initialized");
}
}
public void runBattle() throws InterruptedException {
// Start battle, and run until a contester is dead.
while(player.getHealth() > 0 && enemyMonster.getHealth() > 0) {
int playerStrikeDmg = player.strike();
if(enemyMonster.blockDefend()) {
log.setText( log.getText() + "\n" + player.getName() +" tried to strike " + enemyMonster.getName()+ ", but " + enemyMonster.getName() + " Blocked.");
}else if(enemyMonster.dodgeDefend()) {
log.setText( log.getText() + "\n" + player.getName() +" tried to strike " + enemyMonster.getName()+ ", but " + enemyMonster.getName() + " Blocked.");
}else {
enemyMonster.defend(playerStrikeDmg);
log.setText( log.getText() + "\n" + player.getName() +" strikes " + enemyMonster.getName()+ " for: " + playerStrikeDmg + " left: "+ enemyMonster.getHealth());
}
if(enemyMonster.getHealth() < 1) break;
Thread.sleep(3000);
// Monster Turn
int monsterDmg = enemyMonster.strike();
if(player.blockDefend()) {
log.setText( log.getText() + "\n" + enemyMonster.getName() +" tried to strike " + player.getName()+ ", but " + player.getName()+ " Blocked.");
}else if(player.dodgeDefend()) {
log.setText( log.getText() + "\n" + enemyMonster.getName() +" tried to strike " + player.getName()+ ", but " + player.getName()+ " Dodged.");
}else {
player.defend(monsterDmg);
log.setText( log.getText() + "\n" + enemyMonster.getName() +" strikes " + player.getName()+ " for: " + monsterDmg + " left: "+ player.getHealth());
}
gScreen.updateBot();
Thread.sleep(3000);
}
当我对此进行编码时,我认为它很酷,但我看到有些人只是为了控制线程本身。我刚刚创建了使用Sleep runable的类(代码中没有显示,但它是一个大类)。
这样做会很好,所以我可以在他们问我之前指出我,你知道带走那里的弹药。 :d
希望你们能帮助我:)。
THX
答案 0 :(得分:3)
线程超过4 states。另外,我建议阅读Lesson: Concurrency以获取有关线程的更多信息。
请注意,如果您希望以设定的间隔执行任务,我强烈建议您使用Executors
框架。
答案 1 :(得分:1)
已阻止 - 在超时之前它根本不会运行。 Ready现在'可以运行,但没有可用的处理器可以运行它 - 只要处理器可用就会运行'。
答案 2 :(得分:0)
正如所有其他人所说的,还有更多,这里有一个简单的列表:
如需完整列表,请查看着名的维基百科;) http://en.wikipedia.org/wiki/Process_state