黑马程序员技术交流社区
标题:
线程间的唤醒
[打印本页]
作者:
小虎199406
时间:
2015-7-21 20:17
标题:
线程间的唤醒
package com.itheima2;
public class TheadTest {
public static void main(String[] args) {
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();
}
}
class Input implements Runnable //往资源中存入值
{
private Res r;
Input(Res r){
this.r = r;
}
public void run() {
int x= 0;
while(true)
{
synchronized(r){
if(r.flag)
try { //如果r为true时则等待
r.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(x==0){
r.name = "mike";
r.sex = "man";
}else{
r.name ="丽丽";
r.sex = "女女女女";
}
// x++;
// x=x%2;
x= (x+1)%2;
r.flag= true;
r.notify(); //唤醒r锁属上等待的线程 即唤醒Output中等待的线程
}
}
}
}
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为false时则等待
r.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(r.name+"::::::"+r.sex);
r.flag=false;
r.notify(); //唤醒r锁属上等待的线程 即唤醒Input中等待的线程
}
}
}
}
class Res //被多个线程共同操作的资源
{
String name;
String sex;
boolean flag = false;
}
复制代码
wait();
notify();
notifyAll();
都是用在同步中,因为要对持有监视器(锁)的线程操作.
所以要使用在同步中,因为只有同步才有锁.
为什么这些操作线程的方法又要定义在Object类中呢
因为这些方法在操作同步线程时,都必须要标识他们所操作的线程持有的锁
只有同一个锁上的被等待线程,可以被同一个锁上的notify唤醒.
不可以对不同所中的线程进行唤醒
也就是说等待和唤醒必须是同属一个锁的线程
而锁可以是任意对象,所以可以被任意对象叼哦有那个的方法定义在Object类中
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2