2012-02-09 3 views
0

좋아요, 근본적으로는 제가 작업하고있는 프로그램에 대해 생각해 볼 수있는 가장 어려운 해결 방법을 만들었고 지금은 프로그램 자체 만 제외하고 모든 것이 작동하도록했습니다.자바의 스레드에서 메소드 실행하기

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

그리고 다음 thread2 실행 가능한이 같은 것입니다 : 나는에서 정적 메소드를 호출하고 싶다면, 지금

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

그래서, 여기에 내가 함께 일하고 있어요 코드는 쓰레드가 생성되었습니다. 어떻게 할 수 있습니까? 나는 "bubbleSort"라는 메서드를 가지고 있는데,이 메서드는 생성 된 스레드 내에서 작동하지 않습니다. 도움?

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

// 그러나 나는 실행 영역에 넣을 수없고, 나는 그것이 실행 어디에 외부에서 다른 스레드에 액세스 할 수없는 것, 메소드의 골격입니다. 어어! 어느 스레드가 정적 메서드 호출에서 하나라도 실행 가능한 구현하는 해당 스레드에서 실행되지 않습니다 클래스에서 정적 메소드를 실행 ./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

관련 문제