我有一個同步方法。那麼我將用長時間操作啓動一個Thread,子線程也有一個同步方法,但是在子線程中的synchronized方法將保持synchronized方法的鎖定,這將導致anr在我的應用中。爲什麼在子線程中同步方法保持主線程鎖定
我的代碼是:
import java.util.Date;
public class ThreadTest {
static MQTTThread mThread;
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println("the " + i + " - restart time = "
+ new Date());
restart(i);
}
}
private static synchronized void restart(int i) {
System.out.println("the " + i + " - restart excute " + new Date());
if (null != mThread) {
if (!mThread.isAlive()) {
try {
System.out
.println("Action:restartConnectThread in mThread.runFlag)");
mThread = new MQTTThread();
mThread.setName("MQTTThread");
mThread.start();
// mqttExecutor.execute(mThread);
} catch (Exception e) {
System.out.println("!mThread.runFlag");
}
} else {
System.out.println("Action:restartConnectThread - CONNECTING");
}
} else {
try {
System.out
.println("Action:restartConnectThread in null thread");
mThread = new MQTTThread();
mThread.setName("MQTTThread");
mThread.start();
} catch (Exception e) {
System.out.println("null mThread");
}
}
}
private static class MQTTThread extends Thread {
public void run() {
connectToServer();
System.out.println("connected");
}
}
public static synchronized void connectToServer() {
try {
System.out.println("Thread.sleep " + new Date());
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
運行代碼的結果是: – user3766493
把它放在你的問題。不在評論中。 – awksp
你可以在你打電話的地方寫出原始的android代碼嗎? – carlosvin