1、线程等待:
1)在Object.java中,定义了wait(), notify()和notifyAll()等接口。
2)wait()的作用是让当前线程进入等待状态,同时,wait()也会让当前线程释放它所持有的锁。
3)wait() -- 让当前线程处于“等待(阻塞)状态”,“直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法”,当前线程被唤醒(进入“就绪状态”)。
2、线程唤醒
1)notify()和notifyAll()的作用,则是唤醒当前对象上的等待线程;notify()是唤醒单个线程,而notifyAll()是唤醒所有的线程。
2)notify() -- 唤醒在此对象监视器上等待的单个线程。
3)notifyAll() -- 唤醒在此对象监视器上等待的所有线程。
3、代码举例:
思路:
1)定义一个资源类 Student--->学生资源类属性
2)设置学生的数据(生产者线程) SetThread------>定义具体属性对象
3)获取学生数据(消费者线程) GetThread-------->获取具体属性对象
4)测试类 Test ------->创建线程类对象--->SerThread st = new SetThread(s);
GetThread gt = new GetThread(s);
Thread t1 = new Thread(st);
Thread t2 = new Thread(gt);
package wait_notify;
public class Student {
//定义资源类数据
String name;
int age;
boolean flag;
}
package wait_notify;
//生产者线程
public class SetThread implements Runnable {
// 对象锁
private Student s;
// 有参构造
public SetThread(Student s) {
this.s = s;
// 定义一个变量
}
private int x = 0;
// 重写run()方法
@Override
public void run() {
// 设置学生数据
while (true) {
// 加入同步代码块
synchronized (s) {
// 判断有无数据
if (s.flag) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (x % 2 == 0) {
s.name = "张三";
s.age = 18;
} else {
s.name = "李四";
s.age = 19;
}
x++;
// 如果有数据了,更改flag值
s.flag = true;// 有数据了
// 通知t2线程消费数据,唤醒
s.notify(); // 唤醒t2线程,唤醒之后t1,t2都互相抢占
}
}
}
}
package wait_notify;
//消费者线程
public class GetThread implements Runnable {
// 定义所对象
private Student s;
public GetThread(Student s) {
this.s = s;
}
@Override
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;
// 通知t1线程,赶紧产生数据
// 唤醒单个线程
s.notify();
}
}
}
}
package wait_notify;
//测试类
public class Test {
public static void main(String[] args) {
// 针对同一个对象进行操作(否则会出错)
Student s = new Student();
// 创建线程类对象
SetThread st = new SetThread(s);
GetThread gt = new GetThread(s);
// 创建线程对象
Thread t1 = new Thread(st); // 生产者
Thread t2 = new Thread(gt);// 消费者
// 启动线程
t1.start();
t2.start();
}
}
4、wait(),notify(),notifyAll() 这些方法为什么会定义在Object类中呢?
这些方法好像就属于线程的方法,但是Thread类中并没有这些方法,多线程中同步锁对象:任意的Java类
这些方法都和锁对象有关系,所以定义在Object类