java双线程打印ABAB

main方法内,有两个实线程A和B,A线程只能打印“A”,B线程只能打印“B”,运行该方法后,打印结果为ABABABAB…,交替打印100次。利用join方法实现如下:

public static void main(String[] args) throws InterruptedException{
for(int i = 0; i < 50; i ++){
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
System.out.print("A");
}
});
threadA.start();
threadA.join(0);
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
System.out.print("B");
}
});
threadB.start();
threadB.join(0);
}
}

你可能感兴趣的:(java)