两个线程交替执行打印解决方案
1.Atmoic方式
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Author: 张
* @Date: 2019/1/29 20:19
* @Version: 1.0
* @Description: 1.0
*/
public class ThreadWaitTest {
private final static AtomicInteger numberAtomic = new AtomicInteger(0);
private final static AtomicBoolean boolAtomic = new AtomicBoolean(true);
private final static AtomicInteger zimuAtomic = new AtomicInteger(-1);
public static class ThreadNum implements Runnable {
@Override
public void run() {
while (true) {
if (boolAtomic.get()) {
synchronized (boolAtomic) {
int index1 = numberAtomic.incrementAndGet();
if (index1 < 52) {
int index2 = numberAtomic.incrementAndGet();
System.out.print(index1 + "" + index2);
boolAtomic.set(false);
}else {
break;
}
}
}
}
}
}
public static class ThreadZimu implements Runnable {
@Override
public void run() {
while (true) {
if (!boolAtomic.get()) {
synchronized (boolAtomic) {
int index = zimuAtomic.incrementAndGet();
if(index <= 26){
String zimu = findZimu(index);
System.out.print(zimu);
boolAtomic.set(true);
}else {
break;
}
}
}
}
}
}
public static void main(String[] args) {
Thread number = new Thread(new ThreadNum());
Thread zimu = new Thread(new ThreadZimu());
number.start();
zimu.start();
}
private static String findZimu(int index) {
char a = 'a';
for (int i = 0; i < index; i++) {
a++;
}
return a + "";
}
}
2.通过wait与notifyAll方式
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @Author: 张
* @Date: 2019/2/11 14:41
* @Version: 1.0
* @Description: 1.0
*/
public class ThreadSwitchTest {
public final static AtomicBoolean FLAG = new AtomicBoolean(false);
public static class Number implements Runnable {
@Override
public void run() {
synchronized (FLAG) {
for (int i = 1; i <= 52; i++) {
if (i > 1 && i % 2 == 1) {
System.out.print("");
}
System.out.print(i);
if (i % 2 == 0) {
FLAG.notifyAll();
try {
FLAG.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static class Character implements Runnable {
@Override
public void run() {
synchronized (FLAG) {
for (char i = 'A'; i <= 'Z'; i++) {
System.out.print(i);
FLAG.notifyAll();
try {
FLAG.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Thread numberThread = new Thread(new Number());
Thread characterThread = new Thread(new Character());
numberThread.start();
characterThread.start();
}
}
执行结果:
12a34b56c78d910e1112f1314g1516h1718i1920j2122k2324l2526m2728n2930o3132p3334q3536r3738s3940t4142u4344v4546w4748x4950y5152z