参考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;
}
}
}
}
}
网友评论