对于我们的银行账户,两个线程之间并没有联系,这就会出现余额不足但是还能取钱的状况,为了解决这个问题,我们就使用线程间通信来解决
wait()方法:中断方法的执行,使线程等待
notify()方法:唤醒处于等待的某一线程,使其等待结束
notifyAll()方法:唤醒处于等待的所有线程,使其等待结束
package Threadproj;
public class Consumer implements Runnable {
Queue queue;
Consumer(Queue queue){
this.queue=queue;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
queue.getN();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package Threadproj;
public class Producer implements Runnable{
Queue queue;
Producer(Queue queue){
this.queue=queue;
}
@Override
public void run() {
int i=0;
while(true) {
queue.setN(i++);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package Threadproj;
public class Queue {
private int n;
boolean flag = false;
public int getN() {
// flag为false的时候容器中没有数据了,线程等待
if (!flag) {
try {
synchronized (this) {
this.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("消费" + n);
// 消费完毕,容器中没数据了
flag = false;
notifyAll();
return n;
}
public void setN(int n) {
// flag为true的时候容器中有数据了,线程等待
if (flag) {
try {
synchronized (this) {
this.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("生产" + n);
this.n = n;
// 生产完毕,容器中已经有数据
flag = true;
notifyAll();
}
}
package Threadproj;
public class TestA {
public static void main(String[] args) {
Queue queue = new Queue();
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start();
}
}