线程间通信--生产消费

来源:互联网 发布:php输出当前时间 编辑:程序博客网 时间:2024/05/06 16:25
package thread;


public class Demo1 {


/**
* @线程间通信
* 其实就是多个线程在操作同一个资源,但是操作的动作不同
* 交替输出,可直接运行

*/
public static void main(String[] args) {


Res r = new Res();

new Thread(new Input(r)).start();
new Thread(new Output(r)).start();




}
}


class Res{
private String name;
private String sex;
private boolean flag = false;

public synchronized void set(String name,String sex){
while(flag)
try {this.wait();} catch (InterruptedException e) {}


this.name = name;
this.sex = sex;

flag = true;
this.notifyAll();
}

public synchronized void out(){
while(!flag)
try {this.wait();} catch (InterruptedException e) {}


System.out.println(name+".........."+sex);
flag = false;
this.notifyAll();
}
}


class Input implements Runnable{
Res r = new Res();
Input(Res r){
this.r = r;
}

public void run(){
int x = 0;
while(true){
if(x==0)
r.set("lily", "female");
else
r.set("李明明", "男男男男男男男");
x = (x+1)%2;
}
}
}


class Output implements Runnable{
Res r = new Res();
Output(Res r){
this.r  = r;
}
public void run(){
while(true){
r.out();
}
}
}
0 0
原创粉丝点击