Skip to content

Instantly share code, notes, and snippets.

@fantasticmao
Created January 27, 2021 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fantasticmao/f78ae0016a81877cf5019d9c22c81c73 to your computer and use it in GitHub Desktop.
Save fantasticmao/f78ae0016a81877cf5019d9c22c81c73 to your computer and use it in GitHub Desktop.
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