【问题标题】:Thread and public void run() method in java [duplicate]java中的线程和公共void run()方法[重复]
【发布时间】:2013-10-22 21:01:04
【问题描述】:
    public Thread thread = new Thread();

    public void start() {
        running = true;
        thread.start();
    }

public void run() {

    while(running) {

        System.out.println("test");

        try {
            thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

我的问题是程序不会打印出“测试”,也不会看起来循环,尽管“运行”是真的。有没有办法可以在run方法中不断循环?

【问题讨论】:

  • 您展示的run() 方法实际上是否属于您启动的实际线程子类?

标签: java


【解决方案1】:

您实际上并没有要求给run() 打电话。您所做的只是声明一个与Thread 无关的run() 方法。

将您的 run() 方法放入 Runnable 并将其传递给 Thread

public Thread thread = new Thread(new Runnable() {

    public void run() {

        while (running) {

            System.out.println("test");

            try {
                thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
});

【讨论】:

  • 如果类实现了 Runnable: 'Thread name = new Thread(this);' .如果没有,请将“this”更改为您的可运行文件的名称。您需要将 runnable 传递给线程。编辑:评论了错误的帖子。抱歉,在我的手机上,很难导航。
【解决方案2】:

问题似乎是您没有运行您认为在线程中运行的run 方法。

首先,您创建了一个名为threadThread。在您班级的start 方法中,您将running 设置为true 并调用thread.start()。但这只是调用Thread's run() method, which does nothing

公共无效运行()

如果此线程是使用单独的 Runnable 运行对象,然后调用该 Runnable 对象的 run 方法; 否则,此方法什么都不做并返回。

您没有调用自己的 run 方法。

您已经创建了一个run 方法。我在这里看不到你的类定义,但我假设你的类实现了Runnable。您需要使用Thread constructor that takes a Runnable 将您的类的实例作为参数发送到Thread。然后Thread 就会知道运行你的Runnablerun() 方法。

【讨论】:

    【解决方案3】:

    你需要调用start() 来启动线程。否则running 都不会是真的 thread.start() 也不会被执行。好吧,我猜你打算做这样的事情:

    class MyTask implements Runnable
    {
       boolean running = false;
       public void start() {
            running = true;
            new Thread(this).start();
        }
    
    public void run() {
    
        while(running) {
    
            System.out.println("test");
    
            try {
                Thread.sleep(1000); 
                  // you were doing thread.sleep()! sleep is a static function
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
    }
    
      public static void main(String[] args)
      {
         new MyTask().start();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-03
      • 1970-01-01
      • 2017-07-25
      • 2019-08-26
      • 2015-03-27
      • 2017-02-27
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多