1、使用 lock锁
public class ThreeThreadPrint {
//三个线程分别打印 A,B,C,要求这三个线程一起运行,打印 n 次,输出形如“ABCABCABC....”的字符串
private static ReentrantLock lock = new ReentrantLock();
private static volatile int state = 0;
private static volatile int n = 2;
private static void print(String name,Integer target) {
for (int i = 1; i <= n;) {
lock.lock();
if (state % 3 == target) {
System.out.println(Thread.currentThread().getName()+": "+name);
i++;
state++;
}
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
print("A", 0);
}).start();
Thread.sleep(1000);
new Thread(()->{
print("B", 1);
}).start();
Thread.sleep(1000);
new Thread(()->{
print("C", 2);
}).start();
}
}
Thread-0: A
Thread-1: B
Thread-2: C
Thread-0: A
Thread-1: B
Thread-2: C
2、 使用wait notify 机制
public class ThreeThreadPrint {
//三个线程分别打印 A,B,C,要求这三个线程一起运行,打印 n 次,输出形如“ABCABCABC....”的字符串
private static Object object = new Object();
private static volatile int state = 0;
private static volatile int n = 2000;
private static void print(String name, Integer target) {
for (int i = 1; i <= n; ) {
synchronized (object) {
//判断满足条件不
while (state % 3 != target) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//执行任务
System.out.println(Thread.currentThread().getName() + ": " + name);
i++;
state++;
//通知所有
object.notifyAll();
}
}
}
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
print("A", 0);
}).start();
Thread.sleep(1000);
new Thread(() -> {
print("B", 1);
}).start();
Thread.sleep(1000);
new Thread(() -> {
print("C", 2);
}).start();
}
}