0

如果有一个使用以下代码实现可运行类的类:

public class MyRunnable implements Runnable {
    public Thread t;
    // Other variables;

    public MyRunnable() {
        t = new Thread(this, "MyRunnable Thread");
        // Initialise other variables.
    }

    public void run() {
       //Do something.
    }
}

我正在通过以下方式创建上述类的实例:

public class MyFunc () {
  satic void main (String ards[]) {
     MyRunnable mr = new MyRunnable();
     mr.t.start();


     while (true) {
         Thread.sleep(10000);
         if (!mr.isAlive()) {
              //Execute mr again.
              // How to do it ?
         }
     }
  }
}

我该怎么做?

我有两种方法,但不确定哪一种是正确的:

1.mr.t.start ();

2. MyRunnable mr = new MyRunnable(); mr.t.start();

我应该创建一个新的mr实例吗?

或者我应该使用现有实例还是 mr ?

4

4 回答 4

3

Remove reference to Thread from MyRunnable.

Starting thread idiom in Java looks like this

new Thread(new MyRunnable()).start()

Normal rules of garbage collection applies to cleaning runnables. If no object references runnable it may be garbage collected.

于 2013-06-07T10:00:00.793 回答
1

在 Java 中编写多线程代码有几个习惯用法,请参阅Java 教程。保持简单和独立:

public class YourTask implements Runnable {
   @Override
   public void run() {
      // do something
   }
}

一个最小的示例应用程序:

public class YourApp {

public static void main(final String[] args) throws InterruptedException {

    final YourTask yourTask = new YourTask();
    final Thread thread = new Thread(yourTask);
    thread.start();

    thread.join();
   }
}

小心并发 - 在您有适当的理解之前,您不应该在生产中使用此代码,例如通过阅读Java Concurrency in Practice

于 2013-06-07T10:03:15.353 回答
0

我不喜欢这段代码。

Runnable不应该有一个Thread成员,公共的或私人的。我建议删除它。想得简单:关注点分离。这就是你的 Runnable 应该看起来的样子:

public class MyRunnable implements Runnable {
    public void run() {
       //Do something.
    }
}

而已。让其他知道如何运行事物的类处理该部分。

您最好查看较新的并发包类,例如Executor.

除非您阅读过 Brian Goetz 的“Java Concurrency In Practice”并彻底理解它,否则您不应该尝试进行大量多线程编程。你不太可能遇到麻烦。

于 2013-06-07T09:58:00.733 回答
0

Runnable has the method run(), so you do not need separate Thread inside that.And nothing gets destroyed unless if you go out from the context of your variable (object) definition and you loose the reference.

http://www.javamex.com/tutorials/threads/thread_runnable_construction.shtml

于 2013-06-07T09:59:56.750 回答