黑马程序员技术交流社区
标题:
索
[打印本页]
作者:
hadexs
时间:
2013-5-22 17:44
标题:
索
为什么wait ,notify, notifyAll ,这些方法要定义在object类中?
作者:
Super_Class
时间:
2013-5-22 18:13
class Resource{ <font color="#ff0000">//这里的这个Resource类中封装了线程任务类中要执行的的代码。要实现的是两个线程要交替运行。</font>
String name;
String sex;
boolean flag = true;
public synchronized void put(String name,String sex){
if(!flag){
try {
wait();//当标志位为false,线程wait这里其实是r.wait();<span style="color: rgb(255, 0, 0);">Resource r = new Resource().对象r就要使用wait方法。</span>
} catch (InterruptedException e1){}
}
this.name = name;
this .sex = sex;
flag = false; //执行完后,将标志位状态改变。
notify(); //并且唤醒一个线程这里其实是r.notify();
}
public synchronized void get(){
if(flag){
try {
wait(); //当标志位为true,线程wait。这里其实是r.wait();
} catch (InterruptedException e1){}
}
System.out.println(name+"....."+sex);
flag = true;//执行完后,将标志位状态改变。
notify();//并且唤醒一个线程这里其实是r.notify();
}
}
class Input implements Runnable{
Resource r ;
private int x=0;
Input(Resource r){
this.r = r;
}
public void run(){ //这里有一个线程任务
while(true){
if(x == 0){
r.put("zhangsan","nan");//这里可以将同步代码封装
}else{
r.put("lisi","nv");
}
x = (x+1)%2;
}
}
}
class Output implements Runnable{
Resource r ;
Output(Resource r){
this.r = r;
}
public void run(){ //这里有一个线程任务
while(true){
r.get(); //这里可以将同步代码封装
}
}
}
复制代码
作者:
江大海
时间:
2013-5-22 18:31
因为锁的对象可以是任意类型的,就是synchronized(e)中的e是任意类型的,然后wait notify啊等等都要标明是哪个锁的,所以是Object类的
作者:
王靖远
时间:
2013-5-22 19:48
任意子类都能用的当然就定义在Object(所有类的父类)中了。
await asignal这些就没有定义在Object中了。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2