线程间的通讯
1.线程间的通讯:其实就是多个线程操作同一个资源
2.为什么这些操作线程的方法都要定义在Objec类中呢?
因为这些方法操作同步线程时,都必须 要标识他们线程持有的锁,
只有同一个锁中的被等待线程,可以被同一个锁上的notify锁唤醒。
不可以对不同锁中的线程进行唤醒也就是说等待和唤醒必须是同一个锁,
而锁可以是任意对象,所以被任意对象调用的方法。
public class InputOutDemo {
public static void main(String[] args) {
Res res = new Res();
Thread input = new Thread(new Input(res));
Thread output = new Thread(new Output(res));
input.start();
output.start();
}
}
//资源
class Res {
String name;
String sex;
boolean flag;
//类似于产生资源
public synchronized void set(String name,String sex){
if(flag){
try {this.wait();} catch (InterruptedException e){e.printStackTrace();}
}
this.name = name;
this.sex = sex;
this.notify();
flag = true;
}
//类似于消耗资源
public synchronized void out(){
if(!flag){
try {this.wait();} catch (InterruptedException e){e.printStackTrace();}
}
System.out.println(this.name +"----"+this.sex);
this.notify();
flag = false;
}
}
class Input implements Runnable {
private Res res;
//同步资源
public Input(Res res) {
this.res = res;
}
@Override
public void run() {
int x = 0;
while (true) {
if (x == 0) {
res.set("jack", "男");
} else {
res.set("kally", "女");
}
x = (x + 1) % 2;
}
}
}
class Output implements Runnable {
private Res res;
public Output(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
res.out();
}
}
}