package com.qf.test.one;
public class test03 {
static class Print{
boolean nowA=true;
synchronized void printA(){
while(!nowA){
try {
this.wait();
} catch (Exception e) {
}
}
nowA=false;
System.out.println(Thread.currentThread()+" "+"A");
this.notify();
}
synchronized void printB(){
while(nowA){
try {
this.wait();
} catch (Exception e) {
}
}
nowA=true;
System.out.println(Thread.currentThread()+" "+"B");
this.notify();
}
}
public static class Test3 {
public static void main(String[] args) {
Print print = new Print();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
print.printA();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
print.printB();
}
}
}).start();
}
}
}
两个线程交替打印a和b
最新推荐文章于 2024-05-09 10:35:55 发布