HunderingThooves
HunderingThooves

Reputation: 1002

Executing a method from a thread in java

Okay, so I've basically done the hardest workaround I could think of for the program that I'm working on and now have everything working....except the program itself.

So, here's the code I'm working with:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        Thread thread = new Thread(new thread2());
        public void run() {
            thread.start();
            double startTime = System.nanoTime();
            SortingStuff ss = new SortingStuff();
            ss.setVisible(true);
            double endTime = System.nanoTime();
            double elapsedTime = endTime - startTime;
            System.out.println("This operation took " + elapsedTime + " nanoseconds, which is :" + ((elapsedTime / 1000000) / 1000) + " seconds."); // This will be better later
        }
    });
}

And then the thread2 runnable is something like this:

public static class thread2 implements Runnable{
public void run() {
    System.out.println("thread " +Thread.currentThread().getName());
}

Now, if I wanted to call a static method from the thread created, how could I go about doing that? I have a method called "bubbleSort" that I just can't get to work within the created thread. Help?

    public static void bubbleSort(final String numbers[], final JButton numButton[]){ 

//Is the skeleton for the method, however I can't put it in the run area, and I can't seem to access the other thread from outside of where it's run. UGH!

./Frustrated

Upvotes: 0

Views: 162

Answers (1)

Thomas
Thomas

Reputation: 5094

Running a static method from a class, even one that implements runnable, will not run on that thread, it will run from whichever thread called the static method. Anything that you want to happen in that thread needs to get called from run().

thread2 mythread = new thread2();
new Thread(mythread).start(); //Spawns new thread
thread2.bubbleSort(args); //Runs in this thread, not the spawned one

In response to the comment, I assume you were having problems because you couldn't pass your arguments to the run method. You need to get that data to the thread either before it starts, or through some sort of data stream(file, socket, etc). Here I use the constructor, but it can also be done with a setData(data here) function.

public class Example implements Runnable {
    private dataObject args;

    public Example(dataObject input) {
        args = input;
    }
    public void dosort(dataObject sortArg){contents}

    public void run() {
        dosort(args);
    }
}

public static void main(stuff) { 
    Example myExample = new Example(data);
    //alternate example
    //myExample.setData(data);
    new Thread(myExample).start();
}

Upvotes: 1

Related Questions