一、使用synchronized锁
public class ThreadPrint1 {
private static Integer state = 0;
private static Object lock = new Object();
private static Integer count = 0;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (true) {
synchronized (lock){
if (count < 100 && state == 0 ){
System.out.println(Thread.currentThread()+"A");
count++;
state = 1;
lock.notifyAll();
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
});
Thread t2 = new Thread(() -> {
while (true) {
synchronized (lock){
if (count < 100 && state == 1 ){
System.out.println(Thread.currentThread()+"B");
count++;
state = 2;
lock.notifyAll();
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
});
Thread t3 = new Thread(() -> {
while (true) {
synchronized (lock){
if (count < 100 && state == 2 ){
System.out.println(Thread.currentThread()+"C");
count++;
state = 0;
lock.notifyAll();
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
});
t1.start();
t2.start();
t3.start();
}
}
二、使用ReentrantLock
private static ReentrantLock lock = new ReentrantLock();
private static Integer count = 0;
public static void main(String[] args) {
Condition a = lock.newCondition();
Condition b = lock.newCondition();
Condition c = lock.newCondition();
Thread t1 = new Thread(() -> {
while (true) {
lock.lock();
if (count < 100){
System.out.println(Thread.currentThread()+"A");
count++;
b.signal();
try {
a.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
lock.unlock();
}
});
Thread t2 = new Thread(() -> {
while (true) {
lock.lock();
if (count < 100){
System.out.println(Thread.currentThread()+"B");
count++;
c.signal();
try {
b.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
lock.unlock();
}
});
Thread t3 = new Thread(() -> {
while (true) {
lock.lock();
if (count < 100){
System.out.println(Thread.currentThread()+"C");
count++;
a.signal();
try {
c.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
lock.unlock();
}
});
t1.start();
t2.start();
t3.start();
}