您的位置:首页 > 编程语言 > Java开发

java线程间的通信

2016-03-31 13:43 519 查看
先看代码:

class Producter implements Runnable {
Q q;

public Producter(Q q) {
this.q = q;
}

public void run() {
int i = 0;
while (true) {
synchronized (q) {
if (q.bFull)
try {
q.wait();
} catch (Exception e) {
}
if (i == 1) {
q.name = "zhangsan";
try {
Thread.sleep(1);
} catch (Exception e) {
}
q.sex = "male";
} else {
q.name = "lisi";
q.sex = "female";
}
q.bFull = true;
q.notify();
}
i = (i + 1) % 2;
}
}
}

class Consumer implements Runnable {
Q q;

public Consumer(Q q) {
this.q = q;
}

public void run() {
while (true) {
synchronized (q) {
if (!q.bFull)
try {
q.wait();
} catch (Exception e) {
}
System.out.print(q.name);
System.out.println(":" + q.sex);
q.bFull = false;
q.notify();
}
}
}
}

class Q {
String name = "unkonwn";
String sex = "unkonwn";
boolean bFull = false;
}

class ThreadCommunation {
public static void main(String[] args) {
Q q = new Q();
new Thread(new Producter(q)).start();
new Thread(new Consumer(q)).start();
}
}


运行结果:



这样就实现了线程间的通信,而且通过wait和notify实现交替输出。通过synchronized实现线程间的同步。

上面的代码有点混乱,修改后的更有封装性代码如下:

class Producter implements Runnable {
Q q;

public Producter(Q q) {
this.q = q;
}

public void run() {
int i = 0;
while (true) {
if (i == 0)
q.put("zhangsan", "male");
else
q.put("lisi", "female");
i = (i + 1) % 2;
}
}
}

class Consumer implements Runnable {
Q q;

public Consumer(Q q) {
this.q = q;
}

public void run() {
while (true) {
q.get();
}
}
}

class Q {
private String name = "unkonwn";
private String sex = "unkonwn";
private boolean bFull = false;

public synchronized void put(String name, String sex) {
if (bFull)
try {
wait();
} catch (Exception e) {
}
this.name = name;
try {
Thread.sleep(1);
} catch (Exception e) {
}
this.sex = sex;
bFull = true;
notify();
}

public synchronized void get() {
if (!bFull)
try {
wait();
} catch (Exception e) {
}
System.out.print(name);
System.out.println(":" + sex);
bFull = false;
notify();
}
}

class ThreadCommunation {
public static void main(String[] args) {
Q q = new Q();
new Thread(new Producter(q)).start();
new Thread(new Consumer(q)).start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: