间隔打印A,B:
public class Print {
private boolean nowIsA =true;
synchronized void printA() throws InterruptedException {
// 注意点:如果使用if,会使此处 处于wait状态线程被唤醒,
// 状态改变没有及时响应直接往下执行,可能 出现重复打印A或B;
// 使用while可以再次校验;
// wait:释放锁
// notify:不是马上释放锁,执行完才释放 ,容易出现死锁,用notifyAll解决
while (!nowIsA){
this.wait();
}
System.out.println("A A A A A");
nowIsA = false;
this.notify();
}
synchronized void printB() throws InterruptedException {
while (nowIsA){
this.wait();
}
System.out.println("B B B B B");
nowIsA =true;
this.notify();
}
}public class A extends Thread {
private Print p;
public A(Print p) {
this.p = p;
}
@Override
public void run() {
super.run();
while (true){
try {
p.printA();
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}public class B extends Thread {
private Print p;
public B(Print p) {
this.p = p;
}
@Override
public void run() {
super.run();
while (true){
try {
p.printB();
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}public class Client {
public static void main(String[] args) {
Print print = new Print();
A[]a = new A[5];
B[]b = new B[5];
for(int i=0;i<5;i++){
a[i]= new A(print);
a[i].start();
b[i]= new B(print);
b[i].start();
}
}
}打印效果:
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
本文出自 “11898338” 博客,谢绝转载!
原文地址:http://11908338.blog.51cto.com/11898338/1912187