首页 新闻 会员 周边

java中有关多线程同步问题求大神指教

0
[待解决问题]

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..");
}
}

 

 求大神指教怎样改才能实现这个先计算再输出的功能

飞鱼(Chris)的主页 飞鱼(Chris) | 初学一级 | 园豆:116
提问于:2016-01-17 16:35
< >
分享
所有回答(1)
0

你的代码不就是先计算在输出吗?另外共享的变量尽量使用volatile修饰符或者java.util.concurrent.atomic 包中的类。

芃朋 | 园豆:204 (菜鸟二级) | 2016-01-17 21:56
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册