Skip to content

Instantly share code, notes, and snippets.

@SiAust
Created May 28, 2020 13:23
Show Gist options
  • Save SiAust/3f4fd8e65a2db918325b36a10ce6d0fb to your computer and use it in GitHub Desktop.
Save SiAust/3f4fd8e65a2db918325b36a10ce6d0fb to your computer and use it in GitHub Desktop.
Thread countdown example.
public class Main {
public static void main(String[] args) {
Countdown countdown = new Countdown();
CountdownThread t1 = new CountdownThread(countdown);
t1.setName("Thread 1");
CountdownThread t2 = new CountdownThread(countdown);
t2.setName("Thread 2");
t1.start();
t2.start();
}
}
class Countdown {
private int i;
public void doCountdown() {
String color;
switch(Thread.currentThread().getName()) {
case "Thread 1":
color = ThreadColour.ANSI_CYAN;
break;
case "Thread 2":
color = ThreadColour.ANSI_PURPLE;
break;
default:
color = ThreadColour.ANSI_GREEN;
}
synchronized(this) {
for(i=10; i > 0; i--) {
System.out.println(color + Thread.currentThread().getName() + ": i =" + i);
}
}
}
}
class CountdownThread extends Thread {
private Countdown threadCountdown;
public CountdownThread(Countdown countdown) {
threadCountdown = countdown;
}
public void run() {
threadCountdown.doCountdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment