Mut*_*ing 0 java multithreading this
在我学习线程的过程中,这是按预期工作的
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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当我将线程参数更改为
t1=new Thread (new Game());
Run Code Online (Sandbox Code Playgroud)
程序不再进入run方法.它们不应该是一样的吗?替换"this"关键字的另一种方法应该是什么?
编辑:我从另一个类调用start方法.
甚至在创建实例后将运行变量设置为true,它仍然为false:
public void start(){
t1 = new Thread(new Game());
running = true;
t1.start();
}
Run Code Online (Sandbox Code Playgroud)
它进入run()方法,但它立即从它返回,因为run方法循环而running为true.
在调用时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
}
Run Code Online (Sandbox Code Playgroud)
将其更改为
public void start(){
Game newGame = new Game();
newGame.running = true;
t1 = new Thread(newGame);
t1.start();
}
Run Code Online (Sandbox Code Playgroud)
它会做你期望的.