一、涉及的方法
1、wait():让线程处于冻结状态,被wait的线程会被存储到线程池中。
2、notify():唤醒线程池中的一个线程(任意)。
3、notiyAll():唤醒线程池中的所有线程。
二、注意事项
1、以上涉及的方法都必须定义在同步内;
2、因为这些方法都是用于操作线程的状态,必须要明确到底是操作哪个锁上的线程。
3、为什么操作线程的方法是定义在object类中?
因为这些方法是监视器的方法,其实就是锁的方法,也就是任意对象的方法,所以定义在object类中。
三、代码实例(参考代码:TreadCom2.java)
//等待唤醒机制。单输入,单输出。只有输入完,才输出,输出完,才会重新输入,有相互制约的关系。
class Resourse2 { //表示公共资源
private String name;
private String sex;
private boolean flag = false;
//表示数据的输入方法
public synchronized void set(String name, String sex) {
if (flag)
try { //t0
this.wait(); //true表示有数据,则休眠
} catch (InterruptedException e) {
}//不能加else,因为醒来之后就要继续向下做事
this.name = name;
this.sex = sex;
flag = true;
this.notify();//唤醒对方
}
//表示数据输出的方法
public synchronized void out() {
if (!flag)
try { //t0
this.wait(); //没有数据,则休眠
} catch (InterruptedException e) {
}
System.out.println(name + "。。。输出。。。" + sex);
flag = false;
this.notify();
}
}
class Input2 implements Runnable {
Resourse2 r;
int x = 0;
Input2(Resourse2 r) //保证同一个对象,同一个资源
{
this.r = r;
}
//输入线程的run方法
public void run() {
while (true) {
if (x == 0) {//交替输出
r.set("小明", "男");
} else {
r.set("lili", "nnnnnnnnn");
}
x = (++x) % 2;
}
}
}
class Output2 implements Runnable {
Resourse2 r;
Output2(Resourse2 r) //保证同一个对象,同一个资源
{
this.r = r;
}
//输出线程的方法
public void run() {
while (true) {
r.out();
}
}
}
public class TreadCom2 {
public static void main(String[] args) {
//同一资源
Resourse2 r = new Resourse2();
//不同任务
Input2 i = new Input2(r);
Output2 o = new Output2(r);
//多个线程
Thread t1 = new Thread(i);
Thread t2 = new Thread(o);
t1.start();
t2.start();
}
}
输出结果:
小明。。。输出。。。男
lili。。。输出。。。nnnnnnnnn
小明。。。输出。。。男
lili。。。输出。。。nnnnnnnnn
小明。。。输出。。。男
lili。。。输出。。。nnnnnnnnn
小明。。。输出。。。男
.
.
.