class Digital{
private volatile int i =0;
private volatile long total =0;
private boolean completed = false;
public void increase(){
synchronized(this){
System.out.println(Thread.currentThread().getName()+" is increasing"); //辅助观看结果的 ,可以注释掉
if(++i <= 10)
total += i;
else{
this.completed = true;
this.notifyAll(); //唤醒主线程
}
}
}
public long getTotal(){
return this.total;
}
public boolean isCompleted(){
return this.completed;
}
}
public class DigitalIncrease extends Thread {
Digital digital = null;
DigitalIncrease(Digital digtal){
this.digital = digtal;
start();
}
public void run(){
while(true){
if(digital.isCompleted())
break; //如果加法操作已经完成了 就退出线程
digital.increase();
}
}
public static void main(String [] args){
Digital digital = new Digital();
DigitalIncrease [] diArray = new DigitalIncrease[10];
for(int i = 0; i<10; i++){
diArray[i]= new DigitalIncrease(digital); //创建10个线程
}
//如果加法没完成就让主线程等待
try {
synchronized (digital){
while(!digital.isCompleted())
digital.wait();
}
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(digital.getTotal());
}
}
07-16
07-16
07-16
07-16
07-16
07-16
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交