两个线程交替打印1-99
Posted CoderY
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两个线程交替打印1-99相关的知识,希望对你有一定的参考价值。
参考https://github.com/crossoverJie/JCSprout/blob/master/src/main/java/com/crossoverjie/actual/TwoThread.java从线程方面实现交替打印。
public class Test {
volatile boolean isEven = false;
@org.junit.Test
public void testfda() throws InterruptedException {
Thread a = new Thread(new OddThread(), "thread-1");
Thread b = new Thread(new EvenThread(), "thread-2");
a.start();
b.start();
Thread.sleep(5000);
}
class OddThread implements Runnable {
@Override
public void run() {
int i = 1;
while (i < 100) {
if (!isEven) {
System.err.println(Thread.currentThread().getName() + ":" + i);
i = i + 2;
isEven = true;
}
}
}
}
class EvenThread implements Runnable {
@Override
public void run() {
int i = 2;
while (i < 100) {
if (isEven) {
System.err.println(Thread.currentThread().getName() + ":" + i);
i = i + 2;
isEven = false;
}
}
}
}
}
以上是关于两个线程交替打印1-99的主要内容,如果未能解决你的问题,请参考以下文章