黑马程序员技术交流社区
标题:
请大家看看程序错在那里?
[打印本页]
作者:
RockLee
时间:
2015-7-2 13:49
标题:
请大家看看程序错在那里?
public class 线程的例子之四线程的通讯问题 {
public static void main(String[] args) {
Person p = new Person();
Thread a = new Thread(new productor(p), "生产者");
Thread b = new Thread(new Consumer(p), "消费者");
a.start();
b.start();
}
}
class Person {
private String name;
private String sex;
Boolean flag = false;
Person(String name,String sex){
this.name = name;
this.sex = sex;
}
public Person() {
// TODO Auto-generated constructor stub
}
public void setNmae(String name){
this.name = name;
}
public void setSex(String sex){
this.sex = sex;
}
public String getName(){
return this.name;
}
public String getSex(){
return this.sex;
}
}
class productor implements Runnable {
int i;
Person p;
productor(Person p){
this.p = p;
}
@Override
public void run() {
synchronized (p) {
while(p.flag == true){
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(i%2 == 0){
p.setNmae("小红");
p.setSex("女");
System.out.println(Thread.currentThread().getName()+"生产了"+p.getName()+p.getSex());}
else
{ p.setNmae("小明");
p.setSex("男");
System.out.println(Thread.currentThread().getName()+"生产了"+p.getName()+p.getSex());}
i++;
p.flag = true;
p.notifyAll();
}
}
}
class Consumer implements Runnable{
Person p;
Consumer(Person p){
this.p = p;
}
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (p) {
while(p.flag == false){
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"消费了"+p.getName()+p.getSex());
p.flag = false;
p.notifyAll();
}
}
}
复制代码
作者:
RockLee
时间:
2015-7-2 15:02
:):):):):)
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2