public class Result {
private int value;
private boolean isWait=false;
public void setFlag(boolean isWait){
this.isWait=isWait;
}
public boolean getFlag(){
return this.isWait;
}
public void set(int value){
this.value=value;
}
public int get(){
int v=value;
return v;
}
}
class Counter extends Thread{
private Result res;
public Counter(String name,Result res){
super(name);
this.res=res;
}
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int sum=0;
for(int i=1;i<=100;i++){
sum+=i;
}
res.set(sum);
while(!res.getFlag()){
try {
sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (res) {
res.notifyAll();
}
System.out.println(getName()+
"set num end...");
}
}
//print
class Printer extends Thread{
private Result res;
public Printer(String name,Result res){
super(name);
this.res=res;
}
public void run() {
synchronized (res) {
if(!res.getFlag()){
res.setFlag(true);
try {
res.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(getName()+" get res:"+res.get());
}
}
public class CalcaterTest {
public static void main(String[] args) {
System.out.println("main begin...");
Result r=new Result();
Counter c=new Counter("cal:", r);
Printer p=new Printer("print:", r);
c.start();
p.start();
System.out.println("main eend..");
}
}
求大神指教怎样改才能实现这个先计算再输出的功能