黑马程序员技术交流社区
标题:
多线程中的通信问题、、、
[打印本页]
作者:
yting_xmei1129
时间:
2013-9-25 23:32
标题:
多线程中的通信问题、、、
下面是代码--->
package yting.day11.thread;
public class ThreadCommunication {
public static void main(String[] args) {
Resource r = new Resource();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
class Resource {
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable {
private Resource r;
public Input(Resource r) {
super();
this.r = r;
}
@Override
public void run() {
int f = 0;
while (true) {
synchronized (r) {
if(r.flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (f == 0) {
r.name = "zhangsan";
r.sex = "男";
} else {
r.name = "lili";
r.sex = "女";
}
f = (f + 1) % 2;
r.flag = true;
notify();
}
}
}
}
class Output implements Runnable {
private Resource r;
public Output(Resource r) {
super();
this.r = r;
}
@Override
public void run() {
while (true) {
synchronized (r) {
if(!r.flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(r.name + "..." + r.sex);
r.flag = false;
notify();
}
}
}
}
复制代码
下面是运行结果--->
Exception in thread "Thread-0" zhangsan...男
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at yting.day11.thread.Input.run(ThreadCommunication.java:49)
at java.lang.Thread.run(Thread.java:662)
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at yting.day11.thread.Output.run(ThreadCommunication.java:78)
at java.lang.Thread.run(Thread.java:662)
复制代码
一直抱这个异常,怎么回事啊?坐等大神指导、、、谢了先!
作者:
肖亚光
时间:
2013-9-27 15:33
synchronized (r)
既然你同步的是这个对象,你就应该调用这个对象的wait() notify()方法 去告知线程等待和唤醒
package com.test;
public class Demo1 {
public static void main(String[] args) {
Resource r = new Resource();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
class Resource extends Thread{
String name;
String sex;
boolean flag = false ;
}
class Input extends Thread {
private Resource r;
public Input(Resource r) {
super();
this.r = r;
}
@Override
public void run() {
int f = 0;
while (true) {
synchronized (r) {
if (r.flag) {
try {
r.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (f == 0) {
r.name = "zhangsan";
r.sex = "男";
} else {
r.name = "lili";
r.sex = "女";
}
f = (f + 1) % 2;
r.flag = true;
r.notify();
}
}
}
}
class Output extends Thread {
private Resource r;
public Output(Resource r) {
super();
this.r = r;
}
@Override
public void run() {
while (true) {
synchronized (r) {
if (!r.flag) {
try {
r.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(r.name + "..." + r.sex);
r.flag = false;
r.notify();
}
}
}
}
复制代码
你试试
作者:
yting_xmei1129
时间:
2013-9-27 15:36
肖亚光 发表于 2013-9-27 15:33
synchronized (r)
既然你同步的是这个对象,你就应该调用这个对象的wait() notify()方法 去告知线程等待和 ...
谢谢了,后来饿才发现弄错了呢!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2