问题:两个线程,线程1输出A,线程2输出B,控制两个线程交替输出5次AB
/**
* @author HC
* @version 2011
*/
public class ThreadTest{
private synchronized void printA() {//syn:进入该方法便获得该对象锁,其他线程不能进入该对象的其他同步方法
for (int i = 0; i < 5; ++i)
{
try {
System.out.println("A");
this.notify(); //唤醒任意在等待t对象的线程进入资源竞争状态(当前就B在等待)
this.wait(); //释放资源,并进入等待,别的线程notify才能被唤醒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void printB() {
for (int i = 0; i < 5; ++i){
try {
System.out.println("B");
this.notify();
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadTest t = new ThreadTest();
A thread = t.new A();
thread.start();
try {
thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
B b = t.new B();
b.start();
}
class A extends Thread{//两个内部类,通过外部类对象new这两个线程产生对此外部类对象进行加锁的机制
public void run(){
printA();
}
}
class B extends Thread{
public void run(){
printB();
}
}
}