今天就跟大家聊聊有关使用java怎么实现一个多线程的交替打印,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

notify+wait实现
import org.junit.Test;
import java.util.concurrent.*;
public class TestThreadLocal {
Object o = new Object();
CountDownLatch c=new CountDownLatch(2);
@Test
public void vvvvvvvv() throws InterruptedException {
Thread t1 = new Thread() {
@Override
public void run() {
for (int i = 0; i < 26; i++) {
synchronized (o) {
System.out.print((char) (65 + i));
o.notify();
try {
if(i<25)o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
c.countDown();
}
};
Thread t2 = new Thread() {
@Override
public void run() {
for (int i = 0; i < 26; i++) {
synchronized (o) {
System.out.print(1 + i);
o.notify();
try {
if(i<25)o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
c.countDown();
}
};
t1.start();
t2.start();
//t1.join();
//t2.join();
c.await();
}
}