线程间的通信
针对同一个资源的操作有不同种类的线程
•举例:卖票有进的,也有出的。
代码如下:
(消费者)
package 线程间通信;
public class GetThread implements Runnable{
Student student = null;
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
synchronized (student) {
// if(!student.isHave) {
// try {
// student.wait();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }else {
System.out.println(student.name+" "+student.age);
// student.isHave = false;
// student.notify();
}
}
}
// }
public GetThread() {
}
public GetThread(Student student) {
this.student = student;
}
}
(生产者)
package 线程间通信;
public class SetThread implements Runnable{
Student student = null;
private int n = 0;
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
synchronized (student) {
// if(student.isHave) {
// try {
// student.wait();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
if(n%2==0) {
student.name = "帅气的我";
student.age = 18;
}else {
student.name = "我超级帅的哦";
student.age = 20;
}
n++;
// student.isHave = true;
// student.notify();
}
}
}
public SetThread() {
}
public SetThread(Student student) {
this.student = student;
}
}
(产品类)
package 线程间通信;
public class Student {
public int age;
public String name;
public boolean isHave = false;
}
测试类:
package 线程间通信;
public class Demo {
public static void main(String[] args) {
Student student = new Student();
SetThread setThread = new SetThread(student);
GetThread getThread = new GetThread(student);
Thread thread = new Thread(setThread, "A");
Thread thread2 = new Thread(getThread, "B");
thread.start();
thread2.start();
}
}
运行结果:
这样的结果虽然已经符合线程之间的同步问题,但是却不是我们想要的效果,因为消费者是要等生产者生产完了才可以消费的,而生产者要消费者消费完了才可以生产的,这样才符合逻辑,那么该怎么办呢?这时候就需要线程间的等待唤醒机制来进行解决!
具体代码如上去掉注释,运行结果如下:
这样才符合逻辑啊~~~~