版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/S031302306/article/details/82106620
Student.java
package cn.itcast.productAndConsumer;
public class Student {
private String name;
private int age;
private boolean flag;
public synchronized void setFun(String name, int age){
// 如果有数据,就等待
if(this.flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 设置数据
this.name = name;
this.age = age;
this.flag = true;
this.notify();
}
public synchronized void getFun(){
//如果没有数据,就等待
if(!this.flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//获取数据
System.out.println(this.name+"---"+this.age);
this.flag = false;
this.notify();
}
}
SetThread.java
package cn.itcast.productAndConsumer;
public class SetThread implements Runnable {
private Student s;
private int x = 0;
public SetThread(Student s) {
super();
this.s = s;
}
@Override
public void run() {
while (true) {
if (x % 2 == 0) {
s.setFun("林青霞",27);
}else{
s.setFun("王江", 18);
}
x++;
}
}
}
GetThread.java
package cn.itcast.productAndConsumer;
public class GetThread implements Runnable {
private Student s;
public GetThread(Student s) {
super();
this.s = s;
}
@Override
public void run() {
while(true){
s.getFun();
}
}
}
ProductAndConsumerDemo.java
package cn.itcast.productAndConsumer;
/***
* 等待唤醒:
* Object类中提供了三个方法:
* wait() 等待
* notify() 唤醒单个线程
* notifyAll() 唤醒所有线程
*
* 为什么这些方法不定义在Thread类中?
* 这些方法的调用必须通过锁对象调用,而我们刚才使用的锁对象是任意锁对象
* 所以这些方法必须定义在Object类中
*
*/
public class ProductAndConsumerDemo {
public static void main(String[] args) {
//创建资源
Student s = new Student();
//生产者和消费者
SetThread st1 = new SetThread(s);
GetThread st2 = new GetThread(s);
//线程类
Thread t1 = new Thread(st1);
Thread t2 = new Thread(st2);
t1.start();
t2.start();
}
}