51,410
社区成员
发帖
与我相关
我的任务
分享
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();
}
}
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状态