我有一个线程正在等待处理程序线程创建一个它将初始化指针的对象。我读到你无法同步指针的引用变化。我该怎么做呢?
我首先尝试让线程返回对象,但仍然无法正常工作。 这是我到目前为止所拥有的。 “dataHolder”是正在创建的对象,我想等待。 “lThread”是主题2
主题1:
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();
}
线程2的运行方法:
MariaDB [testdb]> DROP TABLE IF EXISTS `test`;
Query OK, 0 rows affected (0.00 sec)
MariaDB [testdb]> CREATE TABLE `test` (
-> `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> `name` CHAR(10),
-> `nameid` VARCHAR(20) AS (CONCAT(`name`, `id`)) VIRTUAL
-> );
Query OK, 0 rows affected (0.00 sec)
MariaDB [testdb]> INSERT INTO `test`
-> (`name`)
-> VALUES
-> ('foo'), ('voda');
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
MariaDB [testdb]> SELECT
-> `id`,
-> `nameid` `name`
-> FROM
-> `test`;
+----+-------+
| id | name |
+----+-------+
| 1 | foo1 |
| 2 | voda2 |
+----+-------+
2 rows in set (0.00 sec)
答案 0 :(得分:1)
试试这个:
Data dataHolder= null;
lThread.setLocked(true);
lThread.run();
while(lThread.isLocked()){
try {
Thread.sleep(3000);
}
catch(InterruptedException e){
}
}
dataHolder = lThread.dataHolder;
线程2的运行方法:
//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。您可能只想同步交互点。