Can java classes that can be executed have methods other than run ()?

advertisements

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?

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?

EDIT2: Sorry I miswrote the names here.

EDIT3: I'm currently doing this:

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?

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?


You can implement whatever methods you want. However, you need to make sure the reference uses your class name, and not 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!