Advertisement
jaVer404

level16.lesson13.home02

Sep 13th, 2015
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. package com.javarush.test.level16.lesson13.home02;
  2.  
  3. /* Последовательные выполнения нитей
  4. 1. В методе run после всех действий поставь задержку в 10 миллисекунд. Выведи "Нить прервана", если нить будет прервана.
  5. 2. Сделай так, чтобы все нити выполнялись последовательно: сначала для нити №1 отсчет с COUNT до 1, потом для нити №2 с COUNT до 1 и т.д.
  6. Пример:
  7. #1: 4
  8. #1: 3
  9. ...
  10. #1: 1
  11. #2: 4
  12. ...
  13. */
  14.  
  15. public class Solution {
  16.     public volatile static int COUNT = 4;
  17.  
  18.     public static void main(String[] args) throws InterruptedException {
  19.         for (int i = 0; i < COUNT; i++) {
  20.             new SleepingThread().join();
  21.             //напишите тут ваш код
  22.  
  23.         }
  24.     }
  25.  
  26.     public static class SleepingThread extends Thread {
  27.         private volatile int countDownIndex = COUNT;
  28.         private static volatile int threadCount = 0;
  29.  
  30.         public SleepingThread() {
  31.             super(String.valueOf(++threadCount));
  32.             start();
  33.         }
  34.  
  35.         public void run() {
  36.             try {
  37.             while (true) {
  38.                 System.out.println(this);
  39.                 if (--countDownIndex == 0) return;
  40.                 //add sleep here - добавь sleep тут
  41.                 sleep(10);
  42.             }
  43.             }catch (InterruptedException e) {
  44.                 System.out.println("Нить прервана");
  45.             }
  46.         }
  47.  
  48.         public String toString() {
  49.             return "#" + getName() + ": " + countDownIndex;
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement