public class Test_AB {
public static void main(String[] args) {
AB p = new AB();
//th1线程
Thread th1 = new Thread() {
@Override
public void run() {
try {
p.a();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//th2线程
Thread th2 = new Thread() {
@Override
public void run() {
try {
p.b();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//启动线程
th1.start();
th2.start();
}
}
class AB{
private int flag = 0; //标志位
//a方法
public void a() throws Exception {
for (int i = 0; i < 20; i++) {
synchronized (this) { //synchronized关键字修饰非静态方法this,线性同步
while (flag != 0) {
this.wait(); //锁释放,进入等待
}
System.out.println("th1:" + "A");
flag = 1; //修改标志,让th2执行
this.notify(); //唤醒另一个线程
}
}
}
//b方法
public void b() throws Exception {
for (int i = 0; i < 20; i++) {
synchronized (this) {
while (flag != 1) {
this.wait();
}
System.out.println("th2:" + "B");
flag = 0;
this.notify();
}
}
}
}
两个线程循环打印A和B,例如线程A输出A,线程B输出B,一次按顺序循环输出ABABABABAB……
最新推荐文章于 2024-05-09 10:35:55 发布