日期:2014-05-20 浏览次数:21192 次
class Res{//资源
String name;
String sex;
boolean flag = false;//标记,后面会用到
}
class Input implements Runnable{//Thread-0
private Res r;
Input(Res r){
this.r = r;
}
public void run() {
int x = 0;
while(true){
synchronized(r){//锁是r
if(r.flag)//标记为真,就wait
try {
r.wait();
} catch (Exception e) {
}
//否则flag是假
if(x == 0){
r.name = "zhangsan";
r.sex = "male";
}
else{
r.name = "lisi";
r.sex = "female";
}
}
x = (x + 1) % 2;
r.flag = true;//将flag修改为真,
r.notify();//之后唤醒Thread-1
//抛异常:Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
//at java.lang.Object.notify(Native Method)
//at cn.range.multithreadsnext.Input.run(A_Ipc.java:52)
}
}
}
class Output implements Runnable{
private Res r;
Output(Res r){
this.r = r;
}
public void run(){
while(true){
synchronized(r){//和Thread-0用的一个锁,因为下面是创建了一个
//公共的Res r,在Input和Output两个类初始化的时候,传入
//到其中的
if(!r.flag)//flag是false就wait
try {
r.wait();
} catch (Exception e) {
}
System.out.println(r.name + r.sex);
r.flag = false;//否则就在执行完之后,将flag修改为false
r.notify();//唤醒,注意:此处没(来得及)抛异常
}
}
}
}
public class A_Ipc {
public static void main(String[] args) {
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread tin = new Thread(in);
Thread tout = new Thread(out);
tin.start();
tout.start();
}
}