一、初阶版
A、B、C线程顺序打印C、B、A
public class Test {
public static void main(String[] args) {
Thread c=new Thread(()->{
System.out.println("C");
});
Thread b=new Thread(()->{
try {
//等C线程执行完毕后再执行B线程
c.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("B");
});
Thread a=new Thread(()->{
try {
//等B线程执行完毕后再执行A线程
b.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("A");
});
a.start();
b.start();
c.start();
}
}
执行结果:
二、进阶版
按顺序打印十次A、B、C
例如:
使用一个锁对象进行控制,如果满足要求进行打印,打印后释放所有的同类锁,让其他线程竞争。如果不满足题意,则进行wait()等待,(wait的作用是将当前锁释放),同类锁竞争。
代码:
public class ThreadTest {
// 计数器
private static volatile int count= 0;
public static void main(String[] args) {
// 定义一个锁对象
Object lock = new Object();
// 创建三个线程,并指定线程名,每个线程名分别用A,B,C表示
Thread t1 = new Thread(() -> {
// 循环10次
for (int i = 0; i < 10; i++) {
// 执行的代码加锁
synchronized (lock) {
// 每次唤醒后都重新判断是否满足条件
// 每条线程判断的条件不一样,注意线程t1,t2
while (count % 3 != 0) {
try {
// 不满足输出条件时,主动等待并释放锁
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 满足输出条件,打印线程名,每条线程打印的内容不同
System.out.print("A");
// 累加计数
count++;
// 唤醒其他线程
lock.notifyAll();
}
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (count % 3 != 1) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("B");
count++;
lock.notifyAll();
}
}
});
Thread t3 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (count % 3 != 2) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 换行打印
System.out.println("C");
count++;
lock.notifyAll();
}
}
});
// 启动线程
t1.start();
t2.start();
t3.start();
}
}
执行结果: