Skip to content

Instantly share code, notes, and snippets.

@P1n3appl3
Last active March 9, 2017 18:58
Show Gist options
  • Save P1n3appl3/576690845953f2ad71321f3d2f63dd33 to your computer and use it in GitHub Desktop.
Save P1n3appl3/576690845953f2ad71321f3d2f63dd33 to your computer and use it in GitHub Desktop.
Demo of the runnable interface and stopping/restarting threads
import java.util.Scanner;
/*
While running:
enter 1 to print the current random number from the thread
enter 2 to terminate the current thread, which should leave it existing
so you can access the random number even though it wont change
enter 3 to restart the thread (note that the runnable class was not reinstantiated)
*/
public class main {
public static void main(String[] args) {
TestThread r = new TestThread();
Thread thread = new Thread(r, "initial thread");
thread.start();
Scanner reader = new Scanner(System.in);
int uniqueID = 0;
while(true) {
System.out.print("Enter a number: ");
int n = reader.nextInt();
if(n==2) {
r.terminate();
}
else if(n==3) {
uniqueID++;
thread = new Thread(r, "new thread id = " + Integer.toString(uniqueID));
thread.start();
}
else{
System.out.println("Current num: " + r.getNum());
}
}
}
}
import java.util.Random;
public class TestThread implements Runnable {
private int num;
private Random rand;
private boolean enabled;
TestThread(){
rand = new Random();
System.out.println("Constructing runnable in: " + Thread.currentThread().getName());
}
public void run() {
System.out.println("Running thread: " + Thread.currentThread().getName());
enabled = true;
while(enabled) {
num = rand.nextInt(50) + 1;
}
}
public int getNum(){
return num;
}
public void terminate(){
enabled = false;
System.out.println("Disabling thread");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment