题目
创建三个线程,按指定顺序打印1到100,具体如下:
- 线程1打印1
- 线程2打印2
- 线程3打印3
- 线程1打印4
- 线程2打印5
- 线程3打印6
- ……
- 线程3打印99
- 线程1打印100
知识点:wait()/notifyAll()
代码
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author: LiQiang
* @date: 2023/03/30
* @description: 三个线程按顺序打印1到100
*/
public class Main {
// 锁
private static Object resource = new Object();
// 打印区分标识(值为1~3,初始设置1)
private static int flag = 1;
// 需要打印的值
static AtomicInteger integer = new AtomicInteger(1);
// private static volatile int number = 1;
public static void main(String[] args) {
// 三个线程按顺序打印1~100
new Thread(new Runnable() {
@Override
public void run() {
while (integer.get() <= 100) {
synchronized (resource) {
while (flag != 1) {
try {
resource.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 打印操作
if (integer.get() <= 100) {
System.out.println(Thread.currentThread().getName() + " --- " + integer.getAndIncrement());
} else {
Thread.currentThread().interrupt();
// break;
}
// number ++;
// 变更标识
flag = 2;
// 通知线程2
resource.notifyAll();
}
}
}
}, "线程1").start();
new Thread(new Runnable() {
@Override
public void run() {
while (integer.get() <= 100) {
synchronized (resource) {
while (flag != 2) {
try {
resource.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 打印操作
if (integer.get() <= 100) {
System.out.println(Thread.currentThread().getName() + " --- " + integer.getAndIncrement());
} else {
Thread.currentThread().interrupt();
// break;
}
// 变更标识
flag = 3;
// 通知线程3
resource.notifyAll();
}
}
}
}, "线程2").start();
new Thread(new Runnable() {
@Override
public void run() {
while (integer.get() <= 100) {
synchronized (resource) {
while (flag != 3) {
try {
resource.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 打印操作
if (integer.get() <= 100) {
System.out.println(Thread.currentThread().getName() + " --- " + integer.getAndIncrement());
} else {
Thread.currentThread().interrupt();
// break;
}
// 变更标识
flag = 1;
// 通知线程1
resource.notifyAll();
}
}
}
}, "线程3").start();
}
}
本文作者:
whtli
本文链接: https://hexo.whtli.cn/archives/45fd9871.html
版权声明: 遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
本文链接: https://hexo.whtli.cn/archives/45fd9871.html
版权声明: 遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。