public class ThreadThreadp{
public static String TAG = "ThreadThreadp";
private int flag = 0;
public synchronized void printa() throws InterruptedException{
while(true){
if(flag==0){
Log.d(TAG,"A");
flag = 1;
notifyAll();
}
wait();
}
}
public synchronized void printb() throws InterruptedException{
while(true){
if(flag==1){
Log.d(TAG,"B");
flag = 2;
notifyAll();
}
wait();
}
}
public synchronized void printc() throws InterruptedException{
while(true){
if(flag==2){
Log.d(TAG,"C");
flag = 0;
notifyAll();
}
wait();
}
}
public static void main(){
ThreadThreadp t = new ThreadThreadp();
PrintA printA = new PrintA(t);
PrintB printB = new PrintB(t);
PrintC printC = new PrintC(t);
Thread t1 = new Thread(printA);
Thread t2 = new Thread(printB);
Thread t3 = new Thread(printC);
t1.start();
t2.start();
t3.start();
}
}
class PrintA implements Runnable{
private ThreadThreadp t;
PrintA(ThreadThreadp t){
this.t = t;
}
@Override
public void run() {
try {
t.printa();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class PrintB implements Runnable{
private ThreadThreadp t;
PrintB(ThreadThreadp t){
this.t = t;
}
@Override
public void run() {
try {
t.printb();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class PrintC implements Runnable{
private ThreadThreadp t;
PrintC(ThreadThreadp t){
this.t = t;
}
@Override
public void run() {
try {
t.printc();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
参考:
notify() 和 notifyAll() 有什么区别?