编写程序,实现三个线程,运行输出 A1 B2 C3 A4 B5 C6 ……、
/**
* @author Mxhlin
* @Email fuhua277@163.com
* @Date 2022/10/09/19:58
* @Version
* @Description 编写程序,实现三个线程,运行输出 A1 B2 C3 A4 B5 C6 …..
*/
public class T10 {
AtomicInteger atomicInteger = new AtomicInteger(0);
ReentrantLock lock = new ReentrantLock(true);
void work(){
String t = Thread.currentThread().getName();
while (true) {
lock.lock();
// synchronized (this){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.printf("%s%d ", t, atomicInteger.incrementAndGet());
if ("C".equals(t)) {
System.out.println();
}
// }
lock.unlock();
}
}
public static void main(String[] args) {
T10 t = new T10();
new Thread(t::work,"A").start();
new Thread(t::work,"B").start();
new Thread(t::work,"C").start();
}
}
运行效果