为什么下面的代码不会导致死锁?我的意思是在我调用getNumber(.)后,类Test的对象应该被锁定,所以我不能访问getNumber2(.).
class Test() {
synchronized int getNumber(int i){
return getNumber2(i);
}
synchronized int getNumber2(int i) {
return i;
}
public static void main(String[] args) {
System.out.println((new Test()).getNumber(100));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
100
Run Code Online (Sandbox Code Playgroud) 我想在java中编写一些代码,以确定给定的URL是文件还是目录.我怎样才能做到这一点??
假设我有一个Object Foo,希望通过使用侦听器接口的几个正在运行的Thread实例获得通知.例如
界面:
public interface ThreadListener {
public void onNewData(String blabla);
}
Run Code Online (Sandbox Code Playgroud)
Foo类:
public class Foo implements ThreadListener {
public Foo() {
FooThread th1 = new FooThread();
FooThread th2 = new FooThread();
...
th1.addListener(this);
th2.addListener(this);
...
th1.start();
th2.start();
...
}
@Override
public void onNewData(String blabla) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
线程:
public FooThread extends Thread {
private ThreadListener listener = null;
public void addListener(ThreadListener listener) {
this.listener = listener;
}
private void informListener() {
if (listener != null) {
listener.onNewData("Hello from …Run Code Online (Sandbox Code Playgroud) 如果我们想在Android中获得单个GPS修复,我们实际上使用已知函数requestSingleUpdate()和LocationManager.GPS_PROVIDER,对吧?
现在我正在我的函数getLocation()中打开GPS,但设备不会自动建立连接,除非我手动关闭GPS然后再打开它.requestSingleUpdate()为网络提供商完美无瑕地工作,我只是不知道为什么这不适合GPS修复.
这是我的源代码的一部分:
getLocation()由另一个带有定时器的对象每隔2分钟运行..在getLocation()中,如果GPS和网络打开,它会尝试在第一分钟获得GPS修复,然后如果没有则获取网络位置GPS修复可用.
public boolean getLocation() {
// DEBUG
Log.d("GPS Connection", "Entering getLocation()");
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!gpsEnabled && !networkEnabled)
return false;
if(gpsEnabled && networkEnabled) {
// DEBUG
Log.d("GPS Connection", "Request GPS Data");
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, gpsLocationListener, Looper.getMainLooper());
gpsGetLocationTimeout = new Timer();
gpsGetLocationTimeout.schedule(new GetNetworkLocation(), GPS_MAX_CONNECTION_TIME_MS);
}
...
Run Code Online (Sandbox Code Playgroud)