62,614
社区成员
发帖
与我相关
我的任务
分享
package cn.test.thread;
class Resource {
private String name;
private String sex;
boolean flag = false;
public synchronized void set(String name,String sex){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {//这里加了个else之后,输出的结果不是想要的那种。去掉else,即可。可是为什么呢?请教大神!
this.name = name;
this.sex = sex;
this.notify();
this.flag = true;
}
}
public synchronized void out(){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println(name+"..."+sex);
this.notify();
this.flag = false;
}
}
}
/**
* 资源输入
* @author sea
*
*/
class Input implements Runnable{
Resource r;
public Input(Resource r){
this.r = r;
}
@Override
public void run() {
int num = 0;
while(true){
if(num == 0){
r.set("张三","男");
//System.out.println(Thread.currentThread().getName()+"资源输入");
}else{
r.set("lili", "female");
//System.out.println(Thread.currentThread().getName()+"资源输入");
}
num = ++num%2;
}
}
}
class Output implements Runnable{
Resource r ;
public Output(Resource r){
this.r = r;
}
@Override
public void run() {
while(true){
r.out();
}
}
}
public class InformationTest {
public static void main(String[] args) {
Resource r = new Resource();
Input ip = new Input(r);
Output op = new Output(r);
Thread t1 = new Thread(ip);
Thread t2 = new Thread(op);
t1.start();
t2.start();
}
}