在我学习线程的过程中,这正在按预期工作
public class Game implements Runnable{
//FIELDS
private Thread t1;
boolean running;
//METHODS
public void start(){
running = true;
t1 = new Thread(this);
t1.start();
}
public void run(){
while (running){
System.out.println("runnin");
try {
Thread.sleep(17);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
然后,当我将线程参数更改为
t1=new Thread (new Game());
程序不再进入run方法。 它们不应该是一样的吗?替代“this”关键字的其他方法应该是什么?
编辑:我正在从另一个类调用 start 方法。
即使在创建实例后将运行变量设置为 true,它仍然为 false:
public void start(){
t1 = new Thread(new Game());
running = true;
t1.start();
}
最佳答案
它进入run()
方法,但它立即从该方法返回,因为当running
为true时run方法会循环。
当调用 new Game()
时,您正在构造一个新的不同 Game 实例,其 running
字段为 false。所以循环根本不循环:
public void start(){
running = true; // set this.running to true
t1 = new Thread(new Game()); // construct a new Game. This new Game has another, different running field, whose value is false
t1.start(); // start the thread, which doesn't do anything since running is false
}
更改为
public void start(){
Game newGame = new Game();
newGame.running = true;
t1 = new Thread(newGame);
t1.start();
}
它会做你期望的事情。
关于Java 线程参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17899448/