## java多线程等待唤醒机制的运用(wait(),notifyAll())
解决问题:线程A,线程B,线程C按先后顺序:线程A—>线程B---->线程C 每个线程输出3个数, 比如:线程A (1 2 3)—>线程B(4 5 6)—>线程C(7 8 9)—>线程A(10 11 12)—>线程B(…)直到3个线程输出的数字到100为止
代码示例:
package test;
/**
* 线程A,线程B,线程C按先后顺序:线程A--->线程B---->线程C 每个线程输出3个数,
* 比如:线程A (1 2 3)--->线程B(4 5 6)--->线程C(7 8 9)--->线程A(10 11 12)--->线程B(...)--->
* 直到3个线程输出的数字到100为止
*
* */
public class PrintNumber {
public static volatile boolean flag1 = false;
public static volatile boolean flag2 = true;
public static volatile boolean flag3 = true;
public static volatile Integer count = 0;
public static volatile boolean interupt = true;//线程停止运行的标志
//线程1
public static class ThreadA implements Runnable{
public Object o;
public ThreadA(Object o) {
this.o = o;
}
@Override
public void run() {
synchronized(o){
while(interupt){
while(flag1){
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
print();
flag1 = true;
flag2 = false;//唤醒线程2的标志
o.notifyAll();
}
}
}
}
//线程2
public static class ThreadB implements Runnable{
public Object o;
public ThreadB(Object o) {
this.o = o;
}
@Override
public void run() {
synchronized (o){
while(interupt){
while(flag2){
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
if(count < 100){
print();
}
flag2 = true;
flag3 = false;//唤醒线程3的标志
o.notifyAll();
}
}
}
}
//线程3
public static class ThreadC implements Runnable{
public Object o;
public ThreadC(Object o) {
this.o = o;
}
@Override
public void run() {
synchronized (o){
while(interupt){
while(flag3){
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(count <100){
print();
}
flag3 = true;
flag1 = false;//唤醒线程1的标志
o.notifyAll();
}
}
}
}
//action
public static void print(){
for(int i=0;i<3;i++){
count++;
System.out.println(Thread.currentThread().getName()+": "+count);
if(count==100){
interupt = false;
break;
}
}
}
public static void main(String[] args) {
Object ob = new Object();//线程A,线程B,线程C 共用一把锁
Thread a = new Thread(new ThreadA(ob),"线程A");
Thread b = new Thread(new ThreadB(ob),"线程B");
Thread c = new Thread(new ThreadC(ob),"线程C");
a.start();
b.start();
c.start();
}
}