关于线程的问题,代码如下,为什么只能输出一个people???

XiaopinOo 2017-04-15 10:26:33

class People{
private String name;
private String sex;
private static Boolean isEmpty=Boolean.TRUE;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setPeople(String name,String sex){
synchronized (this) {
while(!isEmpty.equals(Boolean.TRUE)){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name=name;
try {
Thread.currentThread().sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.sex=sex;
isEmpty=Boolean.FALSE;
}
}
public void getPeople(){
synchronized (this) {
while(!isEmpty.equals(Boolean.FALSE)){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
name=this.getName();
sex=this.getSex();
System.out.println(this.name+"------->"+this.sex);
isEmpty=Boolean.TRUE;
}
}
}

class SetPeople implements Runnable{
private People people;
SetPeople(People people){
this.people=people;
}
public void run() {
for (int i = 0; i <100; i++) {
if(i%2==0){
people.setPeople("春哥", "男");
}else{
people.setPeople("凤姐", "女");
}
}
}
}

class GetPeople implements Runnable{
private People people;
public GetPeople(People people){
this.people=people;
}
public void run() {
for (int i = 0; i < 100; i++) {
people.getPeople();
}
}
}

public class text {
public static void main(String[] args) {
People people=new People();
new Thread(new SetPeople(people)).start();
new Thread(new GetPeople(people)).start();
}

}
...全文
204 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
yql1986 2017-04-19
  • 打赏
  • 举报
回复
我将你的代码改一了下

public class text {
	public static void main(String[] args) {
		People people=new People();
		new Thread(new SetPeople(people),"SetPeople-thread").start();
		new Thread(new GetPeople(people),"GetPeople-thread").start();
		
		try {
			TimeUnit.SECONDS.sleep(5);
		} catch (InterruptedException e) { /* ignore */ }
		
		for(Map.Entry<Thread, StackTraceElement[]> entry:Thread.getAllStackTraces().entrySet()){
			Thread t=entry.getKey();
			System.out.println(t.getName()+" =>"+t.getState().toString());
		}
	}

}
======================控制台输出============================ 春哥------->男 Attach Listener =>RUNNABLE GetPeople-thread =>WAITING SetPeople-thread =>WAITING Finalizer =>WAITING Reference Handler =>WAITING main =>RUNNABLE Signal Dispatcher =>RUNNABLE 线程都处于waiting状态
zjs91 2017-04-16
  • 打赏
  • 举报
回复
isEmpty.equals(Boolean.TRUE) 布尔类型的判断 用equals方法..... 看着真奇怪
九七77 2017-04-15
  • 打赏
  • 举报
回复
你的线程跑一次,就结束了。100次运行,都是在更改同一个对象。所以最后只能输出一个。 不知道你想问什么,你是不是想存100个people?可以声明people[100]数组,或是使用ArrayList等进行存储

51,411

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧