java 线程内部使用sleep导致主程序退出。
三线程顺序输出从1-100
一个主类,函数内部创建三个线程。
相关代码
package concurrent.order.threeThread;
import org.apache.log4j.Logger;
import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private static Logger log = Logger.getLogger(Main.class);
@Test
void main() {
final Three[] flag = {Three.ONE};
Lock lock = new ReentrantLock();
final Condition oneCondition = lock.newCondition();
final Condition twoCondition = lock.newCondition();
final Condition threeCondition = lock.newCondition();
AtomicInteger integer = new AtomicInteger();
integer.getAndIncrement();
Thread thread1 = new Thread(() -> {
for (; integer.get() < 100; ) {
lock.lock();
while (flag[0] != Three.ONE) {
try {
oneCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info(integer.getAndIncrement());
flag[0] = Three.TWO;
twoCondition.signal();
lock.unlock();
}
});
Thread thread2 = new Thread(() -> {
for (; integer.get() < 100; ) {
lock.lock();
while (flag[0] != Three.TWO) {
try {
twoCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info(integer.getAndIncrement());
flag[0] = Three.THREE;
threeCondition.signal();
lock.unlock();
}
});
Thread thread3 = new Thread(() -> {
for (; integer.get() < 100; ) {
lock.lock();
while (flag[0] != Three.THREE) {
try {
threeCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info(integer.getAndIncrement());
flag[0] = Three.ONE;
oneCondition.signal();
lock.unlock();
}
});
thread1.start();
thread2.start();
thread3.start();
}
}
package concurrent.order.threeThread;
public enum Three {
ONE, TWO, THREE
}
结果是正确输出的,但是我想在每个log输出后sleep一段时间
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
但是问题出现了,只是执行了一次thread1 程序即退出了。
请教各位大神,这个是怎么回事呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道你sleep加在哪里出错了,但是我把你的代码运行了一下,也加了按照你说的加了sleep 运行没问题。
我把
logger
换成了System.out.println