2016-03-08 4 views
0

Объект программы состоит в том, чтобы отправить три строки в три отдельных потока и распечатать каждый символ строки по символу. Я хочу, чтобы между каждой входной строкой была пустая строка, но я не уверен, где помещать каждый поток в состояние ожидания или останавливать его, чтобы выход изменялся. В большинстве случаев это комбинация струн перепуталась, иногда один отделяется и выходит аккуратно.Разделение планирования потоков Java

import java.util.Scanner; 

public class Threader { 
    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); 
     System.out.println("Hello"); 
     String str = scan.nextLine(); 
     String str2 = scan.nextLine(); 
     String str3 = scan.nextLine(); 

     Thread A = new Thread(new MyRunnable(str)); 
     A.start(); 

     Thread B = new Thread(new MyRunnable(str2)); 
     B.start(); 

     Thread C = new Thread(new MyRunnable(str3)); 
     C.start(); 
    } 
} 

public class MyRunnable implements Runnable { 
    String str, str2, str3; 
    public MyRunnable(String str){ 
     this.str = str; 
    } 

    @Override 
    public void run() { 
     for (int i = 0; i < str.length(); i++){ 
      System.out.println(str.charAt(i)); 
      try { 
       Thread.sleep(10); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      }   
     } 
    } 
} 
+0

Если вы хотите достичь определенного разделения, вам обязательно придется использовать wait/notify или некоторые виды семафора. – EJP

+1

Я не понимаю, вы хотите, чтобы каждый поток печатал строку, по одному символу в строке, но вы не хотите, чтобы другой поток печатался, будет ли это делать? – Asoub

ответ

-1

Как насчет этого?

import java.util.Scanner; 

public class Threader { 
    public Threader(String str, String str2, String str3) { 
     Thread A = new Thread(new MyRunnable(str)); 
     Thread B = new Thread(new MyRunnable(str2)); 
     Thread C = new Thread(new MyRunnable(str3)); 

     A.start(); 
     B.start(); 
     C.start(); 
    } 

    public synchronized void printString(String str) { 
     for (Character c : str.toCharArray()) { 
      System.out.println(c); 
      try { 
       Thread.sleep(10); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
     System.out.println(); 
    } 

    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); 
     System.out.println("Hello"); 
     String str = scan.nextLine(); 
     String str2 = scan.nextLine(); 
     String str3 = scan.nextLine(); 

     new Threader(str, str2, str3); 
    } 

    class MyRunnable implements Runnable { 
     private String str; 

     public MyRunnable(String str) { 
      this.str = str; 
     } 

     @Override 
     public void run() { 
      printString(str); 
     } 
    } 
} 
+0

Почему проголосовали? Разве этот код не выполняет то, что требует ОП? –

0

Вот ответ, излагает и разделяет каждую строку с промежутками между ними. Забавно, что мой учитель просто хотел, чтобы они начали в одно и то же время, и вывести все смешалось, чтобы продемонстрировать состояние гонки. : p Но вот это, пара, в то время как петли со спит. Ужасно, но оно работает

import java.util.Scanner; 

public class Threader { 

public static void main(String[] args) { 

    Scanner scan = new Scanner(System.in); 
    System.out.println("Enter 3 lines...Suuuuh dude"); 

    /* 
    * Strangs 
    */ 
    String str = scan.nextLine(); 
    String str2 = scan.nextLine(); 
    String str3 = scan.nextLine(); 

    /* 
    * Intantiate threads holding runnable objects 
    */ 
    Thread A = new Thread(new MyRunnable(str)); 
    Thread B = new Thread(new MyRunnable(str2)); 
    Thread C = new Thread(new MyRunnable(str3)); 

    A.start(); 
    // B.start(); 
    // C.start(); 

    /* 
    * try { A.join(); B.join(); C.join(); 
    * 
    * } catch (InterruptedException e) { // TODO Auto-generated catch block 
    * e.printStackTrace(); } 
    */ 

    /* 
    * Uncomment While() Loops To Eliminate race conditions (Threads will 
    * sleep if previous one is Alive(Won't fight for cpu)) 
    */ 

    while (A.isAlive()) { 
     try { 

      B.sleep(1000); 
      System.out.println("\n"); 
     } // end try 
     catch (InterruptedException e) { 
      e.printStackTrace(); 
     } // end catch 
    } // end while 

    B.start(); 
    while (B.isAlive()) { 
     try { 
      C.sleep(1000); 
      System.out.println("\n"); 
     } // end try 
     catch (InterruptedException e) { 
      e.printStackTrace(); 
     } // end catch 
    } // end while 
    C.start(); 
}// main METHOD 

}// Threader CLASS 

// Класс w/Runnable Int.

public class MyRunnable implements Runnable { 

String str, str2, str3; 

public MyRunnable(String str) { 
    this.str = str; 
    this.str2 = str2; 
    this.str3 = str3; 

} 

@Override 
public void run() { 

    for (int i = 0; i < str.length(); i++) { 
     System.out.println(str.charAt(i)); 
     try { 
      // sleep 1 ms before printing next char 
      Thread.sleep(1); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } // for 
    System.out.println("end" + str); 
}// run 

} 
Смежные вопросы