2012-02-09 10 views
0

さて、私は基本的に、私が取り組んでいるプログラムについて考えることができる最も難しい回避策を実行しました。Javaのスレッドからメソッドを実行する

だから、ここで私が働いているコードです:私はからの静的メソッドを呼び出すしたい場合は、今すぐ

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

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 
     } 
    }); 
} 

そして実行可能なスレッド2は、このようなものであるが、スレッドが作成されました、どうすればそれを行うことができますか?私は "bubbleSort"というメソッドを用意していますが、作成したスレッド内では動作できません。助けて?

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

//しかし私は、実行領域にそれを置くことができない、と私はそれを実行していますどこの外から他のスレッドにアクセスすることができないよう、メソッドのスケルトンです。 UGH!どちらのスレッドが静的メソッドを呼び出したから一つでも実行可能な実装し、そのスレッド上で実行されませんクラスの静的メソッドを実行./Frustrated

+0

「bubbleSort」はどこに定義されていますか? – ggreiner

+0

これは、トップレベルのクラスsortingStuffとして知られています – HunderingThooves

+0

このプログラムの完全なコードはここにあります:http://ideone.com/RORWD現在、使用されていないインポートがたくさんあります。 – HunderingThooves

答えて

1

は、それが実行されます。そのスレッドで実行したいものは、run()から呼び出す必要があります。

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

コメントに応じて、あなたは引数をrunメソッドに渡すことができなかったため、問題が発生していると思われます。そのデータを開始する前に、またはある種のデータstream(file, socket, etc)によって、そのデータをスレッドに取得する必要があります。ここではコンストラクタを使用していますが、setData(data here)関数でも行うことができます。

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(); 
} 
+0

それでは、どうやって産卵したスレッドでそれを動かすのですか? – HunderingThooves

+0

答えを例文で更新しました。 – Thomas

関連する問題