public class Solution {
public static final int THREAD_COUNT = 2;
public static void main(String[] args) throws InterruptedException {
Thread[] pool = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
pool[i] = new Thread(new Printer(i));
pool[i].start();
}
for (int i = 0; i < THREAD_COUNT; i++) {
pool[i].join();
}
System.out.println("Job is done");
}
}
public class Printer implements Runnable {
public static final int ROUND = 10;
private int id = 0;
public Printer(int i) {
this.id = i;
}
@Override
public void run() {
for (int i = 0; i < ROUND; i++) {
System.out.print('A');
System.out.print('B');
}
}
}
public class Solution {
public static final int THREAD_COUNT = 2;
public static void main(String[] args) throws InterruptedException {
Thread[] pool = new Thread[THREAD_COUNT];
AtomicBoolean flag = new AtomicBoolean(true);
AtomicInteger counter = new AtomicInteger(1);
for (int i = 0; i < THREAD_COUNT; i++) {
pool[i] = new Thread(new Printer(i, flag, counter));
pool[i].start();
}
for (int i = 0; i < THREAD_COUNT; i++) {
pool[i].join();
}
System.out.println("Job is done");
}
}
public class Solution {
public static final int THREAD_COUNT = 2;
public static void main(String[] args) throws InterruptedException {
runPrintersBusyWaiting();
}
private static void runPrintersBusyWaiting() throws InterruptedException {
Thread[] pool = new Thread[THREAD_COUNT];
AtomicInteger counter = new AtomicInteger(0);
for (int i = 0; i < THREAD_COUNT; i++) {
pool[i] = new Thread(new PrinterBusyWaiting(i, counter, THREAD_COUNT));
pool[i].start();
}
for (int i = 0; i < THREAD_COUNT; i++) {
pool[i].join();
}
System.out.println("\nJob is done");
}
}
class PrinterBusyWaiting implements Runnable {
public static final int ROUND = 10;
private int id = 0;
private final AtomicInteger counter;
private final int n;
public PrinterBusyWaiting(int i, AtomicInteger counter, int n) {
this.id = i;
this.counter = counter;
this.n = n;
}
@Override
public void run() {
for (int i = 0; i < ROUND; i++) {
while (this.counter.get() % (2 * n) != id) {
}
System.out.print('A');
this.counter.getAndIncrement();
while (this.counter.get() % (2 * n) != id + n) {
}
System.out.print('B');
this.counter.getAndIncrement();
}
}
}