Advertisement
jaVer404

level17.lesson02.task02

Sep 24th, 2015
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.54 KB | None | 0 0
  1. package com.javarush.test.level17.lesson02.task02;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. /* Вместе быстрее? Ща проверим :)
  7. 1. Разберись, что и как работает
  8. 2. Создай public static нить SortThread,
  9.    которая в методе run отсортирует статический массив
  10.    testArray используя метод sort
  11. */
  12.  
  13. public class Solution {
  14.     public static int countThreads = 10;//static field (size of )
  15.     public static int[] testArray = new int[1000];//static массив, который нужно посортировать
  16.  
  17.     static {
  18.         for (int i = 0; i < Solution.testArray.length; i++) {
  19.             testArray[i] = i;
  20.         } //раскладыват int от 0 до 999 в масиве testArray
  21.     }
  22.  
  23.     public static void main(String[] args) throws InterruptedException {
  24.         initThreads();
  25.         /*
  26.         * 1. Создает массив на <Thread> размером countThreads (static field)
  27.         *   2.1 Добавляет в массив  10 new SortThread()
  28.         *   2.2 Стартует все  new SortThread() по очереди
  29.         *   2.3 Вызывает join() для каждого элемента по очереди
  30.         * */
  31.     }
  32.  
  33.     public static void initThreads() throws InterruptedException {
  34.         List<Thread> threads = new ArrayList<Thread>(countThreads);
  35.         for (int i = 0; i < countThreads; i++) threads.add(new SortThread());// добавляет new SortThread в List
  36.         for (Thread thread : threads) thread.start();//стартует метод run (сортирует массив на 1000 занчений int)
  37.         for (Thread thread : threads) thread.join();//ждет завержение каждого элемента
  38.     }
  39.  
  40.  
  41.  
  42.     /*
  43.     * в методе run (class SortThread extends Thread) отсортирует статический массив
  44.       testArray используя метод sort
  45.     * */
  46.     public static void sort(int[] array) {
  47.         for (int i = 0; i < array.length - 1; i++) {
  48.             for (int j = i + 1; j < array.length; j++) {
  49.                 if (array[i] < array[j]) {
  50.                     int k = array[i];
  51.                     array[i] = array[j];
  52.                     array[j] = k;
  53.                 }
  54.             }
  55.         }
  56.     }
  57.  
  58.  
  59.     public static class SortThread extends Thread {
  60.         @Override
  61.         public void run()
  62.         {
  63.             sort(testArray);
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement