0
主類:等到線程完成
producer p = new producer();
food me = new food();
me.eat(times,p);
....>Rest of Code<.......
其他類:
class food {
public int times;
public int food;
public boolean canget=false;
boolean done=false;
void eat(int times,producer p){
this.times = times;
p.produce(this);
consumer pe = new consumer();
pe.consume(this);
}
synchronized void add(int n){
while(canget) {
try {
wait();
} catch (Exception e) {
System.out.println("Something nasty happened");
}
}
this.food = n;
System.out.println("Produced food '"+n+"'");
canget = true;
notify();
}
synchronized int get(){
while (!canget){
try{
wait();
}catch (Exception e) {
System.out.println("Something Nasty happened");
}
}
canget = false;
notify();
System.out.println("Eaten food '"+this.food+"'");
return this.food;
}
}
class producer implements Runnable{
int times;
food f;
boolean done;
boolean done(Thread t) {
return done;
}
void produce(food F){
times=F.times;
f=F;
Thread t = new Thread(this);
t.start();
}
public void run() {
while(this.times-- > 0){
f.add(times);
}
}
}
class consumer implements Runnable{
int times;
food f;
void consume(food F){
times=F.times;
f=F;
Thread t = new Thread(this);
t.start();
}
public void run() {
while(this.times-- > 0){
f.get();
}
}
}
該語句後:
me.eat(times,p);
的代碼的其餘部分正在運行,但我想,此前線程由food
,producer
和consumer
完成。我怎樣才能做到這一點?
如果你只是想繼續生產完成後,爲什麼'produce'開始一個新的線程呢? (請注意,如果遵循普通的Java命名約定,則代碼將更易於閱讀......) –
您需要保留對線程的引用,以便可以訪問它們,然後在每個線程上調用「join」。您的主線程將會「加入」該線程的執行。見https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join%28%29 – BretC
@Bret我是新來的,請telll如何做到這一點? – user4785230