黑马程序员技术交流社区
标题:
线程的等待唤醒机制实例一
[打印本页]
作者:
chenyanwei6
时间:
2016-12-23 21:19
标题:
线程的等待唤醒机制实例一
package com.heima.code;
/*
本程序的需求:
读取一条,写出一条
分析:
1.在读取时,首先判断里面是否能写入,也就是标记flag,若为flase,就读取,在读取完之前,唤醒写出线程,若为true,就不读取;
2.在写出时,要在写完之前,唤醒读取线程,因为此时的读取线程正在等待。
3.就这样的交替进行读取和写出操作。
本程序是等待唤醒机制:
* */
class ResourceDemo02{
String name;
String sex;
boolean flag = false;
}
class InputDemo02 implements Runnable{
private ResourceDemo02 resd02;
InputDemo02(ResourceDemo02 resd02){
this.resd02 = resd02;
}
@Override
public void run() {
show();
}
public void show(){
int x=0;
while(true){
synchronized (resd02) {
if(resd02.flag){
try {
resd02.wait();
} catch (Exception e) {
}
if(x==0){
resd02.name = "小红";
resd02.sex = "..................woman";
}else{
resd02.name = "Franke";
resd02.sex = "man";
}
x=(x+1)%2;
}
resd02.flag = true;
resd02.notify();
}
}
}
}
class OutputDemo02 implements Runnable{
private ResourceDemo02 resd02;
OutputDemo02(ResourceDemo02 resd02){
this.resd02 = resd02;
}
@Override
public void run() {
while(true){
synchronized (resd02) {
if(!resd02.flag)
try {
resd02.wait();//等待
} catch (Exception e) {}
System.out.println(resd02.name+"...."+resd02.sex);
resd02.flag = false;
resd02.notify();//唤醒
}
}
}
}
public class InputOutputThreadDemo02 {
public static void main(String[] args) {
ResourceDemo02 resd02 = new ResourceDemo02();
InputDemo02 inPut = new InputDemo02(resd02);
OutputDemo02 outPut = new OutputDemo02(resd02);
Thread tInput = new Thread(inPut);
Thread tOutput = new Thread(outPut);
tInput.start();
tOutput.start();
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2