思路:多线程打印AB,就需要两个线程类,一个线程负责打印一个,调用wait()和notify()方法去控制线程间的通信
package thread;
public class PrintAB {
//声明boolean变量用来控制打印
private boolean flag = false;
//打印A
public synchronized void printA(){while(flag){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("A");
flag = true;
notify();
}
//打印A
public synchronized void printB(){while(!flag){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("B");
flag = false;
notify();
}
//定义打印A的线程类
class A implements Runnable{@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
printA();
}
}
}
//定义打印B的线程类
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<10;i++){
printB();
}
}
}
public static void main(String[] args) {
PrintAB p = new PrintAB();
A a = p.new A();
B b = p.new B();
Thread t = null;
t = new Thread(a);
t.start();
t = new Thread(b);
t.start();
}
}