进程间通信

/*
 * 线程间通信:
 * 其实就是多个线程在操作同一个资源,
 * 但是操作的动作不同。
 *
 *
 * */
class Res {
String name;
String sex;
}

class Input implements Runnable {
private Res r;

// Object obj=new Object();
Input(Res r) {
this.r = r;
}

public void run() {
int x = 0;
// boolean b=true;
while (true) {
synchronized (r) {//Input.class

// System.out.println();
if (x == 0) {
r.name = "凯伦";
r.sex = "男";
} else {
r.name = "丽萨";
r.sex = "女女女女女";
}
x = (x + 1) % 2;
}
}
}
}

class Output implements Runnable {
private Res r;

// Object obj=new Object();
Output(Res r) {
this.r = r;
}

public void run() {
while (true) {
synchronized (r) {//Input.class

System.out.println(r.name + "...." + r.sex);
}
}
}
}

class Demoj {
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 Res {
String name;
String sex;
boolean flag = false;
}

class Input implements Runnable {
private Res r;

// Object obj=new Object();
Input(Res r) {
this.r = r;
}

public void run() {
int x = 0;
// boolean b=true;
while (true) {
synchronized (r) {// Input.class

// System.out.println();
try {

if (r.flag)
wait();
if (x == 0) {
r.name = "凯伦";
r.sex = "男";
} else {
r.name = "丽萨";
r.sex = "女女女女女";
}
x = (x + 1) % 2;
r.flag = true;
notify();// 叫醒线程
} catch (Exception e) {
}
}
}
}
}

class Output implements Runnable {
private Res r;

// Object obj=new Object();
Output(Res r) {
this.r = r;
}

public void run() {
while (true) {
synchronized (r) {// Input.class
try {
if (!r.flag)
wait();

System.out.println(r.name + "...." + r.sex);
r.flag = false;
notify();

} catch (Exception e) {
}
}

}
}
}

public class Demoj {
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();
}
}         

评论

热门博文