概述
三线程顺序输出从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 程序即退出了。
请教各位大神,这个是怎么回事呢?
最后
以上就是拉长大侠为你收集整理的java sleep try_java 线程内部使用sleep导致主程序退出。的全部内容,希望文章能够帮你解决java sleep try_java 线程内部使用sleep导致主程序退出。所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复