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();
}
}
不管是买卖东西,改作业批作业,挖煤采矿,这些都是典型的“生产者消费者”问题,自己google下,找个标准的例子参考。
你想多次输出 不应该用while循环么