黑马程序员技术交流社区
标题:
同步线程中wait();和notify()的用法
[打印本页]
作者:
耿渊博
时间:
2014-3-25 00:50
标题:
同步线程中wait();和notify()的用法
本帖最后由 耿渊博 于 2014-3-25 23:16 编辑
package com.Thread;
class Res{
String name;
String sex;
boolean flag;
}
class Input implements Runnable{
Res r = new Res();
Input(Res r){
this.r = r;
}
public void run(){
int x = 0;
while (true) {
synchronized(r){
if(r.flag)
try {
r.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
if (x == 0) {
r.name = "Mike";
r.sex = "man";
} else {
r.name = "丽丽";
r.sex = "女女女女女";
}
x = (x + 1) % 2;
r.flag = true;
r.notify();
}
}
}
}
class Output implements Runnable{
private Res r;
Output(Res r){
this.r = r;
}
public void run(){
while(true){
synchronized(r){
if(!r.flag)
try {
r.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
System.out.println(r.name+"......."+r.sex);
r.flag = false;
r.notify();
}
}
}
}
public class InputOutputDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
复制代码
作者:
李东梁
时间:
2014-3-25 10:42
1. wait(); 可以让当前线程处于等待,这时的线程被临时存储到了线程池中 ;
2. notify();唤醒线程池中任意一个等待的线程。
3. notifyAll();唤醒线程池中所有的等待线程。
这些方法在使用时,必须定义在同步中,必须被所属同步的锁调用。
如果程序运行到wait();就会进入到线程池中,放弃了CUP的执行权,
当运行到notify();时,是从线程池中唤醒任意一个线程。
还有一点要注意,就是要声明异常;
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2