Android Alarmmanager 同步
线程的可运行看起来像这样
Runnable mTask = new Runnable()
{
public void run()
{
Log.v("service", "thread is running after 5 min");
// Normally we would do some work here... for our sample, we will
// just sleep for 30 seconds.
long endTime = System.currentTimeMillis() + 15*1000;
while (System.currentTimeMillis() < endTime)
{
synchronized (mBinder)
{
try
{
mBinder.wait(endTime - System.currentTimeMillis());
}
catch (Exception e)
{
}
}
} // Done with our work... stop the service!
AlarmService_Service.this.stopSelf();
}
}
我承认我有一些问题同步的概念...线程运行 while 循环等待 15 秒,在该循环中我等待 15 秒。那么,如果我只想编写一个日志条目,例如 Log.v(TAG,TEXT);,那么可运行程序会是什么样子?如果我想将新条目写入自己的数据库表中,会发生什么变化?
谢谢,A.
I am referring to http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/AlarmService_Service.html
There the runnable of the thread looks like this
Runnable mTask = new Runnable()
{
public void run()
{
Log.v("service", "thread is running after 5 min");
// Normally we would do some work here... for our sample, we will
// just sleep for 30 seconds.
long endTime = System.currentTimeMillis() + 15*1000;
while (System.currentTimeMillis() < endTime)
{
synchronized (mBinder)
{
try
{
mBinder.wait(endTime - System.currentTimeMillis());
}
catch (Exception e)
{
}
}
} // Done with our work... stop the service!
AlarmService_Service.this.stopSelf();
}
}
I admit that I have some problems with the concept of synchronized... The thread runs the while loop to wait 15s, within that loop I have wait for 15s. So how would the runnable look like if I just want to write a log entry e.g. Log.v(TAG,TEXT);? What would change if I want to write a new entry into my own database table?
Thanks, A.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只想要一个日志语句,那么以下内容将正常工作。
您是否需要在对象上使用同步取决于对象是否是线程安全的。如果它不是线程安全的,那么您将需要使用同步块确保一次只有一个线程访问该对象。在您的示例中,mBinder 不是线程安全的,因此为了调用绑定器的 wait 方法,您需要确保您是访问它的唯一线程。
runnable
最常用于在不同线程中执行代码,以便长时间运行的操作(例如 IO,但在本例中只是等待)不会阻塞 UI 线程。If you just want a log statement then the following will work fine
Whether you need to use
synchronized
on an object depends on whether object is thread-safe or not. If it is not thread-safe, then you will need to ensure that only one thread access the object at a time by using a synchronized block. In your examplemBinder
is not thread-safe, so in order to call thewait
method of the binder you need to ensure that you are the only thread accessing it.A
runnable
is most often used to execute code in a different thread, so that long running operations (such as IO, but in this case just waiting) do not block the UI thread.简单替换一下
试试
{
mBinder.wait(endTime - System.currentTimeMillis());
}
捕获(异常 e)
{
}
...您要执行的代码?
同步只是断言同一时刻只有一个进程访问该线程。
Simply replace
try
{
mBinder.wait(endTime - System.currentTimeMillis());
}
catch (Exception e)
{
}
...with the code you want to execute?
Synchronized is just to assert that only one process accesses the thread at one time.