yecunhuang123 2015-11-25 15:18 采纳率: 0%
浏览 1233
已结题

java多线程的协调输出结果不符合预期

java新手,拜托看一下下面很简单的多线程协调,就是要求学生交一个作业,老师改一个作业,用一个flag来实现,不知道为什么输出只有一对,
图片说明
代码如下:
package 线程二;
import static java.lang.System.out;
import java.util.LinkedList;

class JobCollection{
LinkedList jobList=new LinkedList();
boolean flag=false;
public synchronized void handInJob(Job job){
try{
if(flag){
wait();
}
else{
jobList.add(job);
out.println("老师, "+job.getStuCode()+"交作业啦!");
flag=true;
notifyAll();
}
}catch(InterruptedException e){}
}
public synchronized void collectJob(){
try{
if(!flag){
wait();
}
else{
Job tpj=jobList.pop();
out.println("ok! "+tpj.getStuCode()+"已交作业!");
Thread.sleep(100);
flag=false;
notifyAll();
}
}catch(InterruptedException e){}
}

}

class Job{
private String stuCode;
Job(String stuCode){
this.stuCode=stuCode;
}

@Override
public boolean equals(Object obj) {  
     if (this == obj)  
            return true;  
     if (obj == null)  
            return false;  
     if (getClass() != obj.getClass())  
            return false; 

     Job other = (Job) obj;  
     if (stuCode != other.stuCode)  
            return false; 
     return true;  
 }  
@Override  
public int hashCode() {  
    final int prime = 31;  
    int result = 1;  
    result = prime * result + Student.stu_num;  
    result = prime * result + ((stuCode == null) ? 0 : stuCode.hashCode());  
    return result;  
}  

public String getStuCode(){
    return stuCode;
}

}
class Student implements Runnable{
private String stuCode;
static int stu_num=0;
static int maxStuNum=10;
private JobCollection job;

public Student(JobCollection job){
    this.job=job;
    stu_num++;
    stuCode="szu2015"+String.format("%03d",stu_num);
}

public void run(){
    try{
        job.handInJob(new Job(stuCode));
        Thread.sleep((int)(Math.random()*500));
    }catch(InterruptedException e){
        e.printStackTrace();
    }
}

}

class Teacher implements Runnable{
private JobCollection job;
public Teacher(JobCollection job){
this.job=job;
}
public void run(){
for(int i=0;i<Student.maxStuNum;i++){
job.collectJob();
}
out.println("Collecting over.");
}
}

public class HandinModel {
public static void main(String[] args){
JobCollection job=new JobCollection();

    Thread[] stu=new Thread[Student.maxStuNum];
    for(int i=0;i<Student.maxStuNum;i++){
        stu[i]=new Thread(new Student(job));
        stu[i].start();
    }
    Thread tea=new Thread(new Teacher(job));
    tea.start();
}

}

  • 写回答

2条回答 默认 最新

  • threenewbee 2015-11-25 15:54
    关注

    不管是买卖东西,改作业批作业,挖煤采矿,这些都是典型的“生产者消费者”问题,自己google下,找个标准的例子参考。

    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码