package ru.job4j.taskBlockCondition;

import com.sun.istack.internal.NotNull;

import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by Alexandr on 09.10.2017.
 */
public class SThreadPool {
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    MyThread[] threads;
    Runnable nRun;
    public SThreadPool() {
        threads = new MyThread[Runtime.getRuntime().availableProcessors()];
        for(MyThread t : threads) {
            t = new MyThread();
            t.start();
        }
    }

    public void add(Runnable r) {
        boolean free = false;
        for(MyThread t : threads) {
            if(!t.getState().equals(Thread.State.BLOCKED) && !t.getState().equals(Thread.State.WAITING)
                    && !t.getState().equals(Thread.State.TIMED_WAITING)) {
                free = true;
                nRun = r;
                break;
            }
        }
        if (!free) {
            try {
                queue.put(r);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    private class MyThread extends Thread {
        @Override
        public void run() {
            Runnable r;
            while (true) {
                if (nRun != null) {
                    r = nRun;
                    r.run();
                    nRun = null;
                } else {
                    try {
                        r = queue.take();
                        r.run();

                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } catch (RuntimeException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }

}

@@ -202,40 +202,87 @@
  * C
-reated by Alexandr on 09.10.2017
+lass for thread pool.%0A * @author atrifonov.%0A * @since 09.10.2017.%0A * @version 1
 .%0A *
@@ -748,167 +748,23 @@
  if(
-!
 t.
-getState().equals(Thread.State.BLOCKED) && !t.getState().equals(Thread.State.WAITING)%0A                    && !t.getState().equals(Thread.State.TIMED_WAITING
+isThreadFree(
 )) %7B
@@ -1109,16 +1109,59 @@
 hread %7B%0A
+        private boolean threadFree = true;%0A
         
@@ -1246,14 +1246,66 @@
 e (t
-rue) %7B
+his.isInterrupted()) %7B%0A                threadFree = false;
 %0A   
@@ -1807,30 +1807,146 @@
       %7D%0A
-%0A            %7D
+                threadFree = true;%0A            %7D%0A        %7D%0A%0A        public boolean isThreadFree() %7B%0A            return threadFree;
 %0A       

edit task 1099