Skip to content

Instantly share code, notes, and snippets.

@pwxcoo
Last active June 18, 2019 01:23
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 pwxcoo/9ef7bbdbc5cbf2bb40b389ecf9d4b205 to your computer and use it in GitHub Desktop.
Save pwxcoo/9ef7bbdbc5cbf2bb40b389ecf9d4b205 to your computer and use it in GitHub Desktop.
Five approaches to print "ABC" 10 times in sequence using 3 threads in Java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerExample {
private AtomicInteger sycValue = new AtomicInteger(0);
private static final int MAX_SYC_VALUE = 3 * 10;
public static void main(String[] args) {
AtomicIntegerExample example = new AtomicIntegerExample();
ExecutorService service = Executors.newFixedThreadPool(3);
service.execute(example.new RunnableA());
service.execute(example.new RunnableB());
service.execute(example.new RunnableC());
service.shutdown();
}
private class RunnableA implements Runnable {
public void run() {
while (sycValue.get() < MAX_SYC_VALUE) {
if (sycValue.get() % 3 == 0) {
System.out.println("A");
sycValue.getAndIncrement();
}
}
}
}
private class RunnableB implements Runnable {
public void run() {
while (sycValue.get() < MAX_SYC_VALUE) {
if (sycValue.get() % 3 == 1) {
System.out.println("B");
sycValue.getAndIncrement();
}
}
}
}
private class RunnableC implements Runnable {
public void run() {
while (sycValue.get() < MAX_SYC_VALUE) {
if (sycValue.get() % 3 == 2) {
System.out.println("C");
sycValue.getAndIncrement();
}
}
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger;
public class ConditionExample {
private Lock lock = new ReentrantLock();
private Condition conditionA = lock.newCondition();
private Condition conditionB = lock.newCondition();
private Condition conditionC = lock.newCondition();
private char currentThreadName = 'A';
private static final Logger logger = Logger.getLogger("ConditionExample");
public static void main(String[] args) {
ConditionExample ce = new ConditionExample();
ExecutorService service = Executors.newFixedThreadPool(3);
service.execute(ce.new ThreadA());
service.execute(ce.new ThreadB());
service.execute(ce.new ThreadC());
service.shutdown();
}
private class ThreadA implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
lock.lock();
try {
while (currentThreadName != 'A') {
try {
conditionA.await();
} catch (InterruptedException e) {
logger.severe(e.getLocalizedMessage());
}
}
// System.out.println(String.format("%d", i + 1));
System.out.println("A");
currentThreadName = 'B';
conditionB.signal();
} finally {
lock.unlock();
}
}
}
}
private class ThreadB implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
lock.lock();
try {
while (currentThreadName != 'B') {
try {
conditionB.await();
} catch (InterruptedException e) {
logger.severe(e.getLocalizedMessage());
}
}
System.out.println("B");
currentThreadName = 'C';
conditionC.signal();
} finally {
lock.unlock();
}
}
}
}
private class ThreadC implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
lock.lock();
try {
while (currentThreadName != 'C') {
try {
conditionC.await();
} catch (InterruptedException e) {
logger.severe(e.getLocalizedMessage());
}
}
System.out.println("C");
currentThreadName = 'A';
conditionA.signal();
} finally {
lock.unlock();
}
}
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PrintThreadExample {
public static void main(String[] args) {
PrintThreadExample example = new PrintThreadExample();
LetterPrinter letterPrint = example.new LetterPrinter();
ExecutorService service = Executors.newFixedThreadPool(3);
service.execute(example.new PrintRunnable(letterPrint, 'A'));
service.execute(example.new PrintRunnable(letterPrint, 'B'));
service.execute(example.new PrintRunnable(letterPrint, 'C'));
service.shutdown();
}
private class LetterPrinter {
private char letter = 'A';
public void print() {
System.out.println(letter);
}
public void nextLetter() {
switch (letter) {
case 'A':
letter = 'B';
break;
case 'B':
letter = 'C';
break;
case 'C':
letter = 'A';
break;
}
}
public char getLetter() {
return letter;
}
}
private class PrintRunnable implements Runnable {
private LetterPrinter letterPrinter = null;
private char letter = ' ';
public PrintRunnable(LetterPrinter letterPrinter, char letter) {
super();
this.letterPrinter = letterPrinter;
this.letter = letter;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (letterPrinter) {
while(letter != letterPrinter.getLetter()) {
try {
letterPrinter.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
letterPrinter.print();
letterPrinter.nextLetter();
letterPrinter.notifyAll();
}
}
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoresExample {
private Semaphore semaphoreA = new Semaphore(1);
private Semaphore semaphoreB = new Semaphore(0);
private Semaphore semaphoreC = new Semaphore(0);
public static void main(String[] args) {
SemaphoresExample example = new SemaphoresExample();
ExecutorService service = Executors.newFixedThreadPool(3);
service.execute(example.new RunnableA());
service.execute(example.new RunnableB());
service.execute(example.new RunnableC());
service.shutdown();
}
private class RunnableA implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
try {
semaphoreA.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("A");
semaphoreB.release();
}
}
}
private class RunnableB implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
try {
semaphoreB.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
semaphoreC.release();
}
}
}
private class RunnableC implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
try {
semaphoreC.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("C");
semaphoreA.release();
}
}
}
}
public class SleepExample extends Thread{
private static int currentCount = 0;
public SleepExample(String name) {
this.setName(name);
}
@Override
public void run() {
while(currentCount < 30) {
switch (currentCount % 3) {
case 0:
if ("A".equals(getName())) {
printAndIncrease();
}
break;
case 1:
if ("B".equals(getName())) {
printAndIncrease();
}
break;
case 2:
if ("C".equals(getName())) {
printAndIncrease();
}
break;
}
}
}
private void printAndIncrease() {
print();
increase();
}
private void print() {
System.out.println(getName());
}
private void increase() {
currentCount++;
}
public static void main(String[] args) {
new SleepExample("A").start();
new SleepExample("B").start();
new SleepExample("C").start();
}
}
@pwxcoo
Copy link
Author

pwxcoo commented Sep 21, 2018

  • sleep
  • synchronized
  • lock
  • semaphore
  • atomic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment