public static void main(String[] args) {
String a="A";
Thread thread1=new Thread(() -> {
synchronized (a){
for(int i=0;i<10;i++){
try {
a.notify();
System.out.println("A");
a.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
a.notifyAll();
}
});
Thread thread2=new Thread(()-> {
synchronized (a){
for(int i=0;i<10;i++){
try {
a.notify();
System.out.println("B");
a.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
a.notifyAll();
}
});
thread1.start();
thread2.start();
}
Java中如何使用两个线程交替打印AB?
于 2024-05-09 10:35:55 首次发布