Tuesday, 15 July 2014

java - why synchronized method in the sub thread hold the lock of main thread -



java - why synchronized method in the sub thread hold the lock of main thread -

i have synchronized method. start thread long time operation, sub-thread have synchronized method, synchronized method in sub thread hold lock of synchronized method cause anr in appliction.

my code is:

import java.util.date; public class threadtest { static mqttthread mthread; public static void main(string[] args) { (int = 0; < 100; i++) { system.out.println("the " + + " - restart time = " + new date()); restart(i); } } private static synchronized void restart(int i) { system.out.println("the " + + " - restart excute " + new date()); if (null != mthread) { if (!mthread.isalive()) { seek { system.out .println("action:restartconnectthread in mthread.runflag)"); mthread = new mqttthread(); mthread.setname("mqttthread"); mthread.start(); // mqttexecutor.execute(mthread); } grab (exception e) { system.out.println("!mthread.runflag"); } } else { system.out.println("action:restartconnectthread - connecting"); } } else { seek { system.out .println("action:restartconnectthread in null thread"); mthread = new mqttthread(); mthread.setname("mqttthread"); mthread.start(); } grab (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() { seek { system.out.println("thread.sleep " + new date()); thread.sleep(20000); } grab (interruptedexception e) { e.printstacktrace(); } } }

it standard behavior of synchronized methods.

look @ http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

it not possible 2 invocations of synchronized methods on same object interleave. when 1 thread executing synchronized method object, other threads invoke synchronized methods same object block (suspend execution) until first thread done object.

so code

public synchronized void method() { }

is equivalent

public void method() { synchronized (this) { } }

for purposes should utilize different lock-objects connecttoserver , restart methods

upd. sorry, missed, methods static. in case specification 8.4.3.6

a synchronized method acquires monitor before executes. class (static) method, monitor associated class object method's class used.

so can not run 2 synchronized methods of class simultaneously, if static

java android multithreading

No comments:

Post a Comment