Created
May 28, 2020 13:23
-
-
Save SiAust/3f4fd8e65a2db918325b36a10ce6d0fb to your computer and use it in GitHub Desktop.
Thread countdown example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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