Skip to content

Commit

Permalink
BAEL-1264 - class and tests for killing a thread (eugenp#3069)
Browse files Browse the repository at this point in the history
  • Loading branch information
egoebelbecker authored and maibin committed Nov 16, 2017
1 parent 34ad3ad commit b30097b
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.baeldung.concurrent.stopping;

import java.util.concurrent.atomic.AtomicBoolean;

public class ControlSubThread implements Runnable {

private Thread worker;
private int interval = 100;
private AtomicBoolean running = new AtomicBoolean(false);
private AtomicBoolean stopped = new AtomicBoolean(true);


public ControlSubThread(int sleepInterval) {
interval = sleepInterval;
}

public void start() {
worker = new Thread(this);
worker.start();
}

public void stop() {
running.set(false);
}

public void interrupt() {
running.set(false);
worker.interrupt();
}

boolean isRunning() {
return running.get();
}

boolean isStopped() {
return stopped.get();
}

public void run() {
running.set(true);
stopped.set(false);
while (running.get()) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
// no-op, just loop again
}
// do something
}
stopped.set(true);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.baeldung.concurrent.stopping;

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class StopThreadTest {

@Test
public void whenStoppedThreadIsStopped() throws InterruptedException {

int interval = 100;

ControlSubThread controlSubThread = new ControlSubThread(interval);
controlSubThread.start();

// Give things a chance to get set up
Thread.sleep(interval);
assertTrue(controlSubThread.isRunning());
assertFalse(controlSubThread.isStopped());

// Stop it and make sure the flags have been reversed
controlSubThread.stop();
Thread.sleep(interval);
assertTrue(controlSubThread.isStopped());
}


@Test
public void whenInterruptedThreadIsStopped() throws InterruptedException {

int interval = 5000;

ControlSubThread controlSubThread = new ControlSubThread(interval);
controlSubThread.start();

// Give things a chance to get set up
Thread.sleep(100);
assertTrue(controlSubThread.isRunning());
assertFalse(controlSubThread.isStopped());

// Stop it and make sure the flags have been reversed
controlSubThread.interrupt();

// Wait less than the time we would normally sleep, and make sure we exited.
Thread.sleep(interval/10);
assertTrue(controlSubThread.isStopped());
}
}

0 comments on commit b30097b

Please sign in to comment.