import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by jenkin
*/
public class ThreadPrintAB {
//简单暴力
public void printAB() {
AtomicBoolean atomicBoolean = new AtomicBoolean(true);
Thread thread = new Thread(() -> {
while (true) {
if (atomicBoolean.get()) {
System.out.printf("A");
atomicBoolean.getAndSet(false);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread1 = new Thread(() -> {
while (true) {
if (!atomicBoolean.get()) {
System.out.printf("B");
atomicBoolean.getAndSet(true);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
thread1.start();
}
//很奇妙的办法
public void printABOptimize() {
Object lock = new Object();
Thread thread = new Thread(() -> {
while (true) {
synchronized (lock) {
System.out.println("A");
try {
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread1 = new Thread(() -> {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
System.out.println("B");
try {
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
thread1.start();
}
}
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by jc6a on 2018/5/8.
* ReentrantLock condition分组
*/
public class Test1 {
public static void main(String[] args) {
ReentrantLock reentrantLock = new ReentrantLock();
Condition condition = reentrantLock.newCondition();
Condition condition1 = reentrantLock.newCondition();
Thread thread = new Thread(()->{
while(true) {
reentrantLock.lock();
try {
System.out.println("A");
condition1.signal();
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
}
});
Thread thread1 = new Thread(()->{
while(true){
reentrantLock.lock();
try{
System.out.println("B");
condition.signal();
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
}
});
thread.start();
thread1.start();
}
}