java java中实现runnable的类可以有run()以外的方法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/497176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:39:21  来源:igfitidea点击:

Can classes in java that implement runnable have methods other than run()?

javamultithreading

提问by u7867

I'm trying to implement a simple class like this:

我正在尝试实现一个像这样的简单类:

public static void main(String args[])
{
    try
    {
        myClass test = new Thread(new myClass(stuff));
        test.start();
        test.join();
    }
    catch (Throwable t) { }
}

When I try to include a print() method in myClass and use it, I get a "cannot find symbol" in class java.lang.Thread. I don't really have to make this a thread, but I would like to, just to test it. Will I have to change it if I want my print() method to work?

当我尝试在 myClass 中包含一个 print() 方法并使用它时,我在类 java.lang.Thread 中得到一个“找不到符号”。我真的不必把它作为一个线程,但我想,只是为了测试它。如果我想让我的 print() 方法工作,我必须改变它吗?

EDIT: I am sorry, I just realized I can call print() inside the run() function lol. Why can't I call it outside though? That doesn't make sense to me. If I add synchronized or something can I call the function outside of run/the class?

编辑:对不起,我刚刚意识到我可以在 run() 函数中调用 print() 大声笑。为什么我不能在外面打电话呢?这对我来说没有意义。如果我添加了 synchronized 或者我可以在运行/类之外调用该函数吗?

EDIT2: Sorry I miswrote the names here.

EDIT2:对不起,我在这里写错了名字。

EDIT3: I'm currently doing this:

EDIT3:我目前正在这样做:

Thread test = new Thread(new myClass(stuff));
teste.start();
teste.join();

If I use new Runner, it seems I can't use start() and join(). Is there a way to go about that?

如果我使用 new Runner,似乎我不能使用 start() 和 join()。有没有办法解决这个问题?

EDIT4: Okay, let's try one more time please: I have myEnvironment, which is a class and I have myAgent, which is another class. myAgent is the thread. myAgent requires a myEnvironment, so I was passing it as a parameter to the constructor. However, I couldn't do this by extending Thread, because constructor (myEnvironment) wasn't found. Do I have to set myEnvironment via another function or can I pass it using the constructor?

EDIT4:好的,让我们再试一次:我有 myEnvironment,它是一个类,我有 myAgent,它是另一个类。myAgent 是线程。myAgent 需要一个 myEnvironment,所以我将它作为参数传递给构造函数。但是,我无法通过扩展 Thread 来做到这一点,因为未找到构造函数 (myEnvironment)。我必须通过另一个函数设置 myEnvironment 还是可以使用构造函数传递它?

回答by Outlaw Programmer

You can implement whatever methods you want. However, you need to make sure the reference uses your class name, and not Runnable:

你可以实现任何你想要的方法。但是,您需要确保引用使用您的类名,而不是 Runnable:

public class MyRunner implements Runnable
{
    @Override public void run();
    public void somethingElse();
}

Runnable r = new MyRunner();
r.somethingElse(); // won't work, this method not defined by Runnable.

MyRunner m = new MyRunner();
m.somethingElse(); // success!

回答by u7867

You have to remember the different classes/interfaces you are using here:

你必须记住你在这里使用的不同的类/接口:

  • Thread
  • Runnable
  • Your subclasses of Runnable or Thread
  • 线
  • 可运行
  • 你的 Runnable 或 Thread 的子类

You can only call methods on a variable if the declared type of the variable has that method. And Runnable objects are not Threads; they are merely code which a Thread can run.

如果变量的声明类型具有该方法,则只能调用该变量的方法。而 Runnable 对象不是线程;它们只是线程可以运行的代码。

Example:

例子:

class MyRunnable implements Runnable() {
  public void run() { /* do run stuff */ }
  public void print() { /* do print stuff */ }
}

class MyThread extends Thread() {
  public void run() { /* do run stuff */ }
  public void print() { /* do print stuff */ }
}

Thread t = new Thread(new MyRunnable());
t.start();
t.print(); // error, t is a Thread not a MyRunnable and not a MyThread
t.join();

MyRunnable mr = new MyRunnable();
mr.run(); // doesn't run in its own thread
mr.print(); // this is ok

Runnable r = new MyRunnable();
r.run(); // doesn't run in its own thread
r.print(); // error, r is defined as Runnable which has no print() method

MyThread mt = new MyThread();
mt.start();
mt.print(); // this is ok because mt is a MyThread
mt.join();

回答by Fortyrunner

You can have additional methods.

您可以使用其他方法。

Your problem seems to be the naming of your variables!!

您的问题似乎是变量的命名!!

回答by Rob Di Marco

Answer to your question is yes they can.

你的问题的答案是肯定的,他们可以。

回答by Peter Lawrey

Can you provide the code where you actually call print() and indicate the scope where print() is defined? Otherwise we would just have to guess what you code looks like. It is very unlikely that your problem has anything do with threads.

您能否提供实际调用 print() 的代码并指明定义 print() 的范围?否则我们只能猜测你的代码是什么样的。您的问题不太可能与线程有关。

回答by Pesto

I think your code in the sample is wrong. This line shouldn't compile if myClass doesn't extend Thread:

我认为您在示例中的代码是错误的。如果 myClass 不扩展线程,则不应编译此行:

myClass test = new Thread(new myClass(stuff));

It probably is something like this, which is giving you errors because Thread doesn't have a print() method:

它可能是这样的,这会给您带来错误,因为 Thread 没有 print() 方法:

Thread test = new Thread(new myClass(stuff));

Instead, do something like this:

相反,请执行以下操作:

public static void main(String args[])
{
    try
    {
        myClass foo = new myClass(stuff);
        myClass test = new Thread(foo);
        test.start();
        test.join();
        foo.print();
    }
    catch (Throwable t) { }
}

回答by klaudio

I faced similar problem, not really a problem but some misunderstanding.

我遇到了类似的问题,不是真正的问题,而是一些误解。

somebody who was working on my code before me created some method and passed Runnable as parameter, more likely:

在我之前处理我的代码的人创建了一些方法并将 Runnable 作为参数传递,更有可能:

void myMethod(Runnable runnable){
runnable.run();
}

Then calling myMethod out of main looks like:

然后从 main 中调用 myMethod 看起来像:

public static void main(String args[])
{
    try
    {
        myMethod(new Runnable(){
                      public void run() {
                          //do something...;
                }});
    }
    catch (Throwable t) { }
}

So, to supply parameter to myMethod I need to instantiate object of (in this case anonymous) class implementing Runnable.

因此,要向 myMethod 提供参数,我需要实例化实现 Runnable 的(在这种情况下是匿名的)类的对象。

My question is: is it necessary to use Runnable in this example? Can I use any different interface? I mean I can create new interface with single method i.e.

我的问题是:在这个例子中是否有必要使用 Runnable?我可以使用任何不同的界面吗?我的意思是我可以用单一方法创建新界面,即

interface MyInterface{ 
void doThis();
}

then change look of myMethod:
void myMethod(MyInterface myObject){
myObject.doThis();
}

And of course client too:

当然还有客户端:

public static void main(String args[])
{
    try
    {
        myMethod(new MyInterface (){
                      public void doThis() {
                          //do something...;
                }});
    }
    catch (Throwable t) { }
}

Or maybe something is about Runnable?!

或者也许是关于 Runnable 的?!