moved daemon thread examples from core-java-concurrency-advanced to core-java-concurrency-advanced-2
This commit is contained in:
@@ -4,3 +4,4 @@
|
||||
|
||||
### Relevant Articles:
|
||||
- [Semaphores in Java](https://www.baeldung.com/java-semaphore)
|
||||
- [Daemon Threads in Java](https://www.baeldung.com/java-daemon-thread)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.concurrent.daemon;
|
||||
|
||||
public class NewThread extends Thread {
|
||||
public void run() {
|
||||
long startTime = System.currentTimeMillis();
|
||||
while (true) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
System.out.println(this.getName() + ": New Thread is running..." + i);
|
||||
try {
|
||||
//Wait for one sec so it doesn't print too fast
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
// prevent the Thread to run forever. It will finish it's execution after 2 seconds
|
||||
if (System.currentTimeMillis() - startTime > 2000) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.concurrent.daemon;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DaemonThreadUnitTest {
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void whenCallIsDaemon_thenCorrect() {
|
||||
NewThread daemonThread = new NewThread();
|
||||
NewThread userThread = new NewThread();
|
||||
daemonThread.setDaemon(true);
|
||||
daemonThread.start();
|
||||
userThread.start();
|
||||
|
||||
assertTrue(daemonThread.isDaemon());
|
||||
assertFalse(userThread.isDaemon());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalThreadStateException.class)
|
||||
@Ignore
|
||||
public void givenUserThread_whenSetDaemonWhileRunning_thenIllegalThreadStateException() {
|
||||
NewThread daemonThread = new NewThread();
|
||||
daemonThread.start();
|
||||
daemonThread.setDaemon(true);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user