Java Thread参数

时间:2013-07-27 15:30:05

标签: 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();
            }
        }
    }



}

然后,当我将线程参数更改为

t1=new Thread (new Game());

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

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

甚至在创建实例后将运行变量设置为true,它仍为false:

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

4 个答案:

答案 0 :(得分:5)

它进入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
}

将其更改为

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

它会做你期望的。

答案 1 :(得分:0)

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

试试这个:

t1=new Thread (new Game());
t1.start();

答案 2 :(得分: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();
        }
    }
}

}

答案 3 :(得分: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();
}
}