等待唤醒机制:
Object类中提供了三个方法:
wait():等待
notify():唤醒单个线程
notifyAll():唤醒所有线程
为什么这些方法不定义在Thread类而定义在Object类中呢?
这些方法的调用必须通过锁对象调用,而我们使用的锁对象是任意锁对象。所以,这些方法必须定义在Object类中。
生产者和消费者多线程体现(线程间通信问题)
生产者:先看是否有数据,有就等待;没有就生产并通知消费者消费
消费者:先看是否有数据,有就消费;没有就等待并通知生产者生产
资源类:Student
设置数据类:SetStudent(生产者)
获取数据类:GetStudent(消费者)
测试类:StudentDemo
public class Student {
String name;
int age;
boolean flag;
}
public class SetStudent implements Runnable {
private Student s;
private int x=0;
public SetStudent(Student s) {
this.s=s;
}
public void run() {
while(true){
synchronized (s) {
if(s.flag){
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(x%2==0){
s.name="huge";
s.age=20;
}else{
s.name="allen";
s.age=21;
}
x++;
s.flag=true;
s.notify();
}
}
}
}
public class GetStudent implements Runnable {
private Student s;
public GetStudent(Student s) {
this.s=s;
}
public void run() {
while(true){
synchronized (s) {
if(!s.flag){
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s.name+s.age);
s.flag=false;
s.notify();
}
}
}
}
public class StudentDemo {
public static void main(String[] args) {
Student s=new Student();
GetStudent gt=new GetStudent(s);
SetStudent st=new SetStudent(s);
Thread t1=new Thread(gt);
Thread t2=new Thread(st);
t1.start();
t2.start();
}
}
输出:
huge20
allen21
huge20
allen21
huge20
allen21
huge20
allen21
...