Java多线程中等待唤醒机制.
wait,notify,notifyAll.三个方法都是对持有锁的线程操作,所以使用在同步过程中.
为什么这些方法定义在Object类中呢?让一个线程等待和唤醒一个线程,必须使用的是同一把锁.不可以对不同锁的线程进行唤醒.而锁可以是任意对象,可以被任意对象调用的方法定义在Object类中.
package com.neutron.thread.wait_notify;
/**
* 线程通信中共享信息类
* @author zhanght
*
*/
public class Resource {
private String name;
private int age;
private boolean flag = false;
public synchronized void setResource(String name, int age) {
if(this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
this.age = age;
flag = true;
this.notify();
}
public synchronized void getResource() {
if (!this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("name:" + this.name + ", age:" + age);
flag = false;
this.notify();
}
public static void main(String[] args){
Resource res = new Resource();
new Thread(new Input(res)).start();
new Thread(new Output(res)).start();
}
}
package com.neutron.thread.wait_notify;
/**
* 数据输入
* @author zhanght
*
*/
public class Input implements Runnable {
private Resource res;
public Input(Resource res) {
this.res = res;
}
@Override
public void run() {
int x = 0;
while(true) {
if (x == 0) {
res.setResource("sky", 11);
} else {
res.setResource("sea", 21);
}
x = (x + 1) % 2;
}
}
}
package com.neutron.thread.wait_notify;
public class Output implements Runnable {
private Resource res;
public Output(Resource res) {
this.res = res;
}
@Override
public void run() {
while(true) {
res.getResource();
}
}
}