Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package xyz.krkw.grpc.demo;
import org.junit.Test;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Copyright © Liu Xiao, 2019
* Created by alex on 2019/4/7.
*/
public class TestTest {
static class PrintRunner implements Runnable {
private final String message;
private final AtomicInteger globalCounter;
private final Semaphore semaphore;
private PrintRunner next;
public PrintRunner(
String message,
AtomicInteger globalCounter
) {
this.message = message;
this.globalCounter = globalCounter;
this.semaphore = new Semaphore(0);
}
@Override
public void run() {
if (next == null) {
System.err.println("You must initialize `next` before running");
return;
}
while (true) {
try {
semaphore.acquire();
} catch (InterruptedException e) {
System.err.println("interrupted: " + e.toString());
e.printStackTrace(System.err);
return;
}
if (globalCounter.getAndDecrement() > 0) {
System.out.println(message);
next.notifyRunner();
} else {
next.notifyRunner();
return;
}
}
}
public PrintRunner getNext() {
return next;
}
public PrintRunner setNext(PrintRunner next) {
this.next = next;
return this;
}
public void notifyRunner() {
semaphore.release();
}
}
@Test
public void test() throws InterruptedException {
int threadCount = 3;
ArrayList<PrintRunner> list = new ArrayList<>(threadCount);
AtomicInteger counter = new AtomicInteger(30);
for (int i = 0; i < threadCount; i++) {
list.add(new PrintRunner(
Character.toString((char) ('A' + i)),
counter
));
}
for (int i = 0; i < threadCount; i++) {
if (i < threadCount - 1) {
list.get(i).setNext(list.get(i + 1));
} else {
list.get(i).setNext(list.get(0));
}
}
ArrayList<Thread> threads = new ArrayList<>(threadCount);
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(list.get(i));
thread.setName("Print thread " + i);
threads.add(thread);
thread.start();
}
list.get(0).notifyRunner();
for (Thread thread : threads) {
thread.join();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment