gpt4 book ai didi

java - 对象创建时的 HandlerThread 同步

转载 作者:行者123 更新时间:2023-12-01 10:45:01 26 4
gpt4 key购买 nike

我有一个线程正在等待处理程序线程创建一个对象,它将初始化一个指向该对象的指针。我读到您无法同步指针的引用更改。我该如何去做呢?

我首先尝试让线程返回对象,但这仍然不起作用。这是我到目前为止所拥有的。“dataHolder”是正在创建的对象,我想等待。“lThread”是线程2

主题 1:

Data dataHolder= null;

lThread.run();
synchronized (lThread) {
while(lThread.locked){

try {

lThread.wait(3000);
}
catch(InterruptedException e){

}
}
dataHolder = lThread.dataHolder;
}

线程2的run方法:

synchronized (this) {

//get gps data
LatLongAlt lla = getLatLonAlt();
if (lla == null) {
return;
}
//create image data holder
dataHolder = new Data(lla, mSensor.getAzimuth(), -1 * mSensor.getPitch(), mSensor.getRoll());
//get four corner geo locations
GeotagActivity gT = new GeotagActivity(dataHolder.getLatLonAlt(), dataHolder.getAzimuth(), dataHolder.getPitch(), dataHolder.getRoll());
//create four corners holder
FourCorners fc = new FourCorners(gT.getTopLeft(), gT.getTopRight(), gT.getBottomLeft(), gT.getBottomRight());
//set four corners
dataHolder.setFourCorners(fc);
locked = false;
this.notify();
}

最佳答案

试试这个:

Data dataHolder= null;

lThread.setLocked(true);
lThread.run();
while(lThread.isLocked()){

try {

Thread.sleep(3000);
}
catch(InterruptedException e){

}
}
dataHolder = lThread.dataHolder;

线程2的run方法:

        //get gps data
LatLongAlt lla = getLatLonAlt();
if (lla == null) {
return;
}
//create image data holder
dataHolder = new Data(lla, mSensor.getAzimuth(), -1 * mSensor.getPitch(), mSensor.getRoll());
//get four corner geo locations
GeotagActivity gT = new GeotagActivity(dataHolder.getLatLonAlt(), dataHolder.getAzimuth(), dataHolder.getPitch(), dataHolder.getRoll());
//create four corners holder
FourCorners fc = new FourCorners(gT.getTopLeft(), gT.getTopRight(), gT.getBottomLeft(), gT.getBottomRight());
//set four corners
dataHolder.setFourCorners(fc);
setLocked(false);
this.notify();

为锁定创建 getter 和 setter:

public synchronized boolean isLocked() {
return locked;
}

public synchronized void setLocked(boolean locked) {
this.locked = locked;
}

基本上,您通过同步 lThread 上的整个进程来永远锁定它。您假设仅同步交互点。

关于java - 对象创建时的 HandlerThread 同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34233331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com