|
| 1 | +package com.baeldung.concurrent.stopping; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import static org.junit.Assert.assertFalse; |
| 6 | +import static org.junit.Assert.assertTrue; |
| 7 | + |
| 8 | +public class StopThreadTest { |
| 9 | + |
| 10 | + @Test |
| 11 | + public void whenStoppedThreadIsStopped() throws InterruptedException { |
| 12 | + |
| 13 | + int interval = 100; |
| 14 | + |
| 15 | + ControlSubThread controlSubThread = new ControlSubThread(interval); |
| 16 | + controlSubThread.start(); |
| 17 | + |
| 18 | + // Give things a chance to get set up |
| 19 | + Thread.sleep(interval); |
| 20 | + assertTrue(controlSubThread.isRunning()); |
| 21 | + assertFalse(controlSubThread.isStopped()); |
| 22 | + |
| 23 | + // Stop it and make sure the flags have been reversed |
| 24 | + controlSubThread.stop(); |
| 25 | + Thread.sleep(interval); |
| 26 | + assertTrue(controlSubThread.isStopped()); |
| 27 | + } |
| 28 | + |
| 29 | + |
| 30 | + @Test |
| 31 | + public void whenInterruptedThreadIsStopped() throws InterruptedException { |
| 32 | + |
| 33 | + int interval = 5000; |
| 34 | + |
| 35 | + ControlSubThread controlSubThread = new ControlSubThread(interval); |
| 36 | + controlSubThread.start(); |
| 37 | + |
| 38 | + // Give things a chance to get set up |
| 39 | + Thread.sleep(100); |
| 40 | + assertTrue(controlSubThread.isRunning()); |
| 41 | + assertFalse(controlSubThread.isStopped()); |
| 42 | + |
| 43 | + // Stop it and make sure the flags have been reversed |
| 44 | + controlSubThread.interrupt(); |
| 45 | + |
| 46 | + // Wait less than the time we would normally sleep, and make sure we exited. |
| 47 | + Thread.sleep(interval/10); |
| 48 | + assertTrue(controlSubThread.isStopped()); |
| 49 | + } |
| 50 | +} |
0 commit comments