Java 线程参数

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

最佳答案

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

相关文章:

java - 流写入异常

java - AudioClip没有声音-Java

javascript - 如何在不重新绑定(bind) this 的情况下返回带有粗箭头函数的对象?

java - Java 模型的 JSON 字段映射

java - 如何从文件名集合中推断出模式?

multithreading - Haskell - 基于 Actor 的可变性

c# - Fire and Forget 没有得到安排

multithreading - 在 grails 中创建临时队列,创建大量临时队列

javascript - Jquery $(this) 范围错误

c++ - 会删除这个调用析构函数吗?