-1

I have an event in the main thread that creates another thread. This new thread must sleep for 60 seconds and then it must check the main thread state. My code is this:

public class Act extends Activity {
    Object lock=new Object();
    public class MainT implements LocationListener {
         public String str="";
         public void onLocationChanged(Location location) {
              synchronized(lock) {
                   str=String.valueOf(location.getLatitude())+" "+String.valueOf(location.getLongitude());
                   new SecondT(str).start();
              }
         }

         class SecondT extends Thread {
              public String st;
              SecondT(String s) {
                   st=s;
              }

              public void run() {
                   waitSeconds();
              }

              public void waitSeconds() {
                   try {
                        Thread.sleep(60000);
                        synchronized(lock) {
                             if (str.equals(st))
                             Log.d("SecondT", "Same string.");
                        }
                   } catch (InterruptedException e) {
                        e.printStackTrace();
                   }
              }
         }

        @Override
        public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
        }
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        MainT mt = new MainT();
        locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 50, mt);
    }
}

The problem is that if a start that thread, it's the MainT that sleeps (the GPS event isn't called even if i pass new coordinates through the debug tool).

4

1 回答 1

1

问题是,如果启动该线程,则 MainT 会休眠(即使我通过调试工具传递新坐标,也不会调用 GPS 事件)。

synchronized正如@Joni 所提到的,除非更新字符串值的代码部分正在执行一些可能需要很长时间的复杂操作,否则很难看到 main 会在哪里休眠。会不会是 main 试图分叉 2 个线程,而第二个线程正在等待锁?如果您提供更多代码,我们可能会看到您的问题。

在分叉线程和主线程之间共享st值方面,您可能会考虑类似AtomicReference<String>. 这将允许您在没有锁定的情况下set(...)获取分叉线程中的值和 main 中的值。get()

于 2013-09-17T17:59:09.670 回答