关于线程同步取得数据的问题。

djwdjw 2005-10-19 05:40:56
有一程序:
public class Test{

TestThread t=new TestThread();
t.start();
System.out.println(t.testValue());

}

public class TestThread extends Thread{
private String testValue;
public void setTestValue(String testValue){
this.testValue=testValue;
}
public String getTestValue(){
return testValue;
}
public void run(){
//some operations
setTestValue("some value");
}

}

System.out.println(t.testValue());这句打印出来的是空值,怎样使得线程执行完成,才去取得testValue的值,怎样达到同步?
...全文
152 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
djwdjw 2005-10-25
  • 打赏
  • 举报
回复
我的解法是:
伪代码:
...WorkThread extends Thread{
private String value;
getValue(){
return value;
}

setValue(String value)
{
this.value=value;
}
....run(){
synchronized(this){
//some operations
notify();
}
}
}

......main(String[] args){
WorkThread wt=new WorkThread();
wt.start();
synchronized(wt){
if (wt.isAlive()){
wt.wait();
}
}
}
System.out.println("value-------->"+wt.getValue());
就可以了。谢谢大家。
djwdjw 2005-10-25
  • 打赏
  • 举报
回复
我的解法是:
伪代码:
...WorkThread extends Thread{

....run(){
synchronized(this){
//some operations
}
}
}

......main(String[] args){
WorkThread wt=new WorkThread();
wt.start();
synchronized(wt){

}

}
djwdjw 2005-10-19
  • 打赏
  • 举报
回复
有道理,我试一下。
zyxzyx10 2005-10-19
  • 打赏
  • 举报
回复
看问题已经解决,只管JF
  • 打赏
  • 举报
回复
mark
chg2008 2005-10-19
  • 打赏
  • 举报
回复
呵呵
stamp80 2005-10-19
  • 打赏
  • 举报
回复
在westarea(彩色的草原) 的run方法最后,添加notifyall,唤醒等待线程。而且class Test 中用if判断就足够了。
djwdjw 2005-10-19
  • 打赏
  • 举报
回复
to believefym(暮色,miss,迷失,miss。。。) :
这只是做一个伪程序,不是真正运行的程序。
to westarea(彩色的草原):
那主线程岂不是要一直在那里while(!t.getFlag()){
Thread.yield();
}做这个操作。
我以前做过,主线程可以等到子线程取到某个值。但现在忘了。
诗海 2005-10-19
  • 打赏
  • 举报
回复
believefym(暮色,miss,迷失,miss。。。) 同志,和我抢分啊:)
楼主的错误我帮他改过来了
believefym 2005-10-19
  • 打赏
  • 举报
回复
楼主这个程序本身就有问题,改好以后有问题再问吧

public class Test{

TestThread t=new TestThread();
t.start();
System.out.println(t.testValue());

}
这个明显是编译通不过的
诗海 2005-10-19
  • 打赏
  • 举报
回复
class Test {
TestThread t = new TestThread();
public void test(){
t.start();
while(!t.getFlag()){
Thread.yield();
}
System.out.println(t.getTestValue());
}
}

class TestThread extends Thread {
private boolean setFlag = false;
private String testValue;
public void setTestValue(String testValue) {
this.testValue = testValue;
}

public String getTestValue() {
return testValue;
}

public void run() {
setTestValue("some value");
setFlag = true;
}

public boolean getFlag(){
return setFlag;
}
}

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧