0

在我学习线程的路上,这是按预期工作的

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());

程序不再进入运行方法。他们不应该是一样的吗?替换“this”关键字的另一种方法应该是什么?

编辑:我正在从另一个类调用 start 方法。

即使在创建实例后将运行变量设置为 true,它仍然是 false:

public void start(){
    t1 = new Thread(new Game());
    running = true;
    t1.start();
}
4

4 回答 4

5

它进入该run()方法,但它立即从该方法返回,因为 run 方法循环 whilerunning为 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
}

将其更改为

public void start(){
    Game newGame = new Game();
    newGame.running = true;
    t1 = new Thread(newGame);
    t1.start();
}

它会做你所期望的。

于 2013-07-27T15:38:13.223 回答
0
public class Game implements Runnable{
//FIELDS
private Thread t1;
boolean running;
//METHODS   
public void start(){
running = true;
t1 = new Thread(new Game());
t1.start();
}
public void run(){
running=true;
while (running){
System.out.println("runnin");
try {
Thread.sleep(17);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
class another{
public static void main(String s[]){
Game t=new Game();
t.start();
}
}
于 2013-07-27T17:03:19.647 回答
0

它进入 run 方法,但是对于使用 new Game() 创建的新对象,变量“running”被初始化为 false。因此,它不会在控制台上打印任何内容。

如果要为对象的另一个实例创建线程,可以尝试以下操作:

public class Game implements Runnable{

//FIELDS
private Thread t1;
boolean running;

//Constructor to set the running boolean
public Game(boolean running)
{
   this.running = running;
}


//METHODS   

public void start(){
    running = true;
    t1 = new Thread(new Game(running));
    t1.start();
}


public void run(){
    while (running){
        System.out.println("runnin");
        try {
            Thread.sleep(17);
        }
        catch (InterruptedException e) {
                    e.printStackTrace();
        }
    }
}

}

于 2013-07-27T15:42:30.087 回答
0

不一样,在第一种情况下,如果您调用 start(),您将创建一个新线程并启动它,但是当您使用 new Thread(new Game()) 时,您需要在新线程上调用 start()。

尝试这个:

t1=new Thread (new Game());
t1.start();
于 2013-07-27T15:35:07.827 回答