Advertisement
jaVer404

level16.lesson05.task01

Sep 8th, 2015
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.97 KB | None | 0 0
  1. package com.javarush.test.level16.lesson05.task01;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. /* join
  7. Подумайте, в каком месте и для какого объекта нужно вызвать метод join,
  8.  
  9. чтобы результат выводился по-порядку
  10. сначала для firstThread,
  11. а потом для secondThread.
  12. Вызовите метод join в нужном месте.
  13. Пример вывода:
  14. firstThread : String 1
  15. firstThread : String 2
  16. ...
  17. firstThread : String 19
  18. firstThread : String 20
  19. secondThread : String 1
  20. ...
  21. secondThread : String 20
  22. */
  23.  
  24. public class Solution {
  25.     public static void main(String[] args) throws InterruptedException {
  26.         PrintListThread firstThread = new PrintListThread("firstThread");
  27.         PrintListThread secondThread = new PrintListThread("secondThread");
  28.         firstThread.start();
  29.         firstThread.join();//second thread can't .start() until firstThread dies
  30.         secondThread.start();
  31.     }
  32. /*---------------------PrintListThread*/
  33.     public static class PrintListThread extends Thread {
  34.         public PrintListThread(String name) {
  35.             super(name);
  36.         }
  37.  
  38.         public void run() {
  39.             printList(getList(20), getName());
  40.         }
  41.     }
  42.  
  43. /*-------------------------------------------------*/
  44.     public static void printList(List<String> list, String threadName) {
  45.         for (String item : list) {
  46.             System.out.println(String.format("%s : %s", threadName, item));
  47.         }
  48.     }
  49. /*-----------------------------------------------------------------*/
  50.     public static List<String> getList(int n) {
  51.         List<String> result = new ArrayList<String>();
  52.         if (n < 1) return result;
  53.  
  54.         for (int i = 0; i < n; i++) {
  55.             result.add(String.format("String %d", (i + 1)));
  56.         }
  57.         return result;
  58.     }
  59.  
  60. /*----------------------------------------------------------------*/
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement