moved daemon thread examples from core-java-concurrency-advanced to core-java-concurrency-advanced-2

This commit is contained in:
fejera
2019-09-29 11:14:11 +02:00
parent 432395628b
commit c98254dbe0
4 changed files with 24 additions and 1 deletions

View File

@@ -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)

View File

@@ -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;
}
}
}
}

View File

@@ -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);
}
}