Created
January 27, 2021 06:29
-
-
Save fantasticmao/f78ae0016a81877cf5019d9c22c81c73 to your computer and use it in GitHub Desktop.
This file contains 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
package cn.fantasticmao.demo.java.lang.concurrent.simulation; | |
import java.util.concurrent.atomic.AtomicInteger; | |
public class TurnPrint { | |
private static class Task implements Runnable { | |
private final char c; | |
private final int remainder; | |
private final AtomicInteger count; | |
public Task(char c, int remainder, AtomicInteger count) { | |
this.c = c; | |
this.remainder = remainder; | |
this.count = count; | |
} | |
@Override | |
public void run() { | |
while (!Thread.currentThread().isInterrupted() | |
&& count.get() < 300) { | |
if (count.get() % 3 == remainder) { | |
System.out.printf("%c%n", c); | |
count.incrementAndGet(); | |
} | |
} | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
AtomicInteger count = new AtomicInteger(0); | |
new Thread(new Task('A', 0, count), "Task-A").start(); | |
new Thread(new Task('B', 1, count), "Task-B").start(); | |
new Thread(new Task('C', 2, count), "Task-C").start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment