Created
May 8, 2015 12:12
-
-
Save wbars/fc1a0c3e4c2c736e10ca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import java.util.ArrayList; | |
import java.util.Stack; | |
/** | |
* Created by wannabe on 08.05.15. | |
*/ | |
public class ThreadHandle { | |
public static final int threadsCount = 10; | |
public static void main(String[] args) throws InterruptedException { | |
final Stack<Thread> threads = new Stack<>(); | |
for (int i = 0; i < threadsCount; i++) { | |
final String index = Integer.toString(i); | |
Thread thread = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
while (true) { | |
try { | |
System.out.println("Hello, i am thread " + index); | |
Thread.sleep(threadsCount * 1000); | |
} catch (InterruptedException e) { | |
System.out.println("Thread " + index + " was closed"); | |
return; | |
} | |
} | |
} | |
}); | |
threads.push(thread); | |
Thread.sleep(1000); | |
thread.start(); | |
} | |
Thread watcher = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
while (!allThreadsDead(threads)) { | |
try { | |
Thread.sleep(4000); | |
threads.pop().interrupt(); | |
} catch (InterruptedException e) { | |
System.out.println("Whos dare to stop watcher?!"); | |
} | |
} | |
} | |
}); | |
watcher.start(); | |
} | |
public static boolean allThreadsDead(Stack<Thread> threads) { | |
for (Thread thread : threads) { | |
if (thread.isAlive()) { | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment