2017-03-25 2 views
2

스레딩 문제가 있는데 어떻게해야하는지 또는 잘못 코딩했는지 확실하지 않습니다. 내가 이해하는 것으로부터, 스레딩은 동시에 여러 가지 방법을 사용해야하며,이 때문에 스레드가 서로 얽혀 있어야합니다. 내 코드는 단일 문자를 사용하여 1000 번 반복하지만 두 문자의 다른 변형을 사용하는 대신 1000 번, "b"를 천 번 반복합니다. 내 문제는 무엇입니까?스레딩이 올바르게 작동하지 않습니까?

홈페이지 방법

import java.util.*; 
public class MainThread { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     Scanner answer = new Scanner(System.in); 

     System.out.println("Give me a single character: "); 
     char h = answer.next().charAt(0); 
     System.out.println("Give me another single character: "); 
     char a = answer.next().charAt(0); 

     MyThread t1 = new MyThread(h); 
     MyThread t2 = new MyThread(a); 

     t1.start(h); 
     t2.start(a);   

     answer.close(); 
    } 
} 

내 스레딩 클래스 모든

import java.util.*; 
public class MyThread extends Thread{ 

    Scanner answer = new Scanner(System.in); 

    public MyThread(char x) { 
     // TODO Auto-generated constructor stub 
    } 


    public void Stored(char x){ 
     System.out.println("Type a single letter here: ");  
    } 


    //modified run method 
    public void start(char x){ 

     for(int i = 0; i < 1000; i++){ 
      System.out.print(x); 
      try { 
       Thread.sleep(1); 
      } catch (InterruptedException e) {    
       e.printStackTrace(); 
      } 
      Thread.yield(); 
     } 
    } 
} 
+0

안녕하세요, 시작 방법이 아닌 실행 방법을 재정의해야합니다. –

답변

0

첫째로, 당신이 올바른 멀티 스레딩을 구현하는 경우에도, 귀하의 기술 문제가 발생할하지 않습니다 보장 아니에요. 하지만 반복해서는 안됩니다.)

해결 방법은 다음과 같습니다. start()가 아니라 run() 메서드를 재정의합니다. 스레드 생성자는 main에서 start()가 호출되고 (인자가있는 새로운 시작 메소드가 없음) 인수를 취해야하며, run()은 병렬로 실행되는 작업을 구현합니다. 따라서 스레드 생성자에서 설정 한 스레드의 필드에 액세스 할 수 있습니다. 당신이 아니라 당신은 start 방법을 순차적으로 호출 한 멀티 스레딩되지 않습니다 짓을 무엇

1

즉, 평행하게 여러 스레드를 실행하기 위해, 당신은 당신의 MyThread 클래스의 run() 메소드를 오버라이드 (override) 할 필요가있다.

중요한 점은 표시된대로 스레드을 start 때 자동으로 run() 방법은 JVM에 의해 호출되며, run() 내부의 코드는 주/다른 스레드와 병렬로 실행됩니다, 그래서 MyThread 클래스 내부 run()을 무시한다는 것입니다 아래 :

class MyThread extends Thread { 

    private char x; 

    public MyThread(char x) { 
     this.x= x; 
    } 

    // Add run() method 
    public void run() { 

     for (int i = 0; i < 10; i++) { 
      System.out.print(x); 
      try { 
       Thread.sleep(500); 
      } catch (InterruptedException e) { 

       e.printStackTrace(); 
      } 
      Thread.yield(); 
     } 
    } 
} 

MainThread 클래스 :

public class MainThread { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     Scanner answer = new Scanner(System.in); 

     System.out.println("Give me a single character: "); 
     char h = answer.next().charAt(0); 
     System.out.println("Give me another single character: "); 
     char a = answer.next().charAt(0); 

     MyThread t1 = new MyThread(h); 
     MyThread t2 = new MyThread(a); 

     t1.start();//this calls run() of t1 automatically 
     t2.start();//this calls run() of t2 automatically   

     answer.close(); 
    } 
} 

Thread을 만들고 시작하는 방법과 멀티 스레딩이 어떻게 작동하는지에 대한 기본적인 이해를 위해 here을 제안하십시오.

1

스레드를 병렬로 실행하려면 start 대신 run 메서드를 구현해야합니다.

Thread.start()를위한 JavaDoc를 참조하십시오

원인 실행을 시작하는이 스레드를; Java 가상 머신은이 스레드의 run 메소드를 이라고 부릅니다. 합니다 (start 메소드에 대한 호출로부터 리턴) 현재 스레드 (run 그 메소드를 실행)가 다른 스레드 :

결과는 두 스레드가 동시에 실행된다는 것이다.

0

오류는 이미 설명되었습니다. run 메서드 대신 start 메서드를 재정의했습니다.어쨌든 Thread 클래스를 확장하는 것은 바람직하지 않다. 왜냐하면 당신은 그 기능을 확장하기를 원하지 않기 때문이다.

public static void main(String[] args) { 
     // ... 
     Thread t1 = new Thread(new MyRunnable(h)); 
     t1.start(); 
    } 

Runnable 오브젝트는 (생산 코드에서 더 나은 이름을 사용) :

당신은 그냥 스레드를 사용하려는 때문에 더 나은 방법 (IMO)는 스레드에의 Runnable을 제공하는 것입니다

public class MyRunnable implements Runnable { 

    private final char ch; 

    public MyRunnable(char theChar) { 
     ch = theChar; 
    } 

    @Override 
    public void run() { 
     for (int i = 0; i < 1000; i++) { 
      ... 
     } 
    } 

이 람다와 함께 사용하여 개선 될 수 있지만, 포인트는 여기

더되지 않습니다 : "implements Runnable" vs. "extends Thread"

관련 문제