Java 继续之前如何等待
Java how to wait before going on
我希望我的 runnable 在重新开始之前等待几秒钟,关于如何做到这一点有什么建议吗?
如果我使用 this.wait();它不起作用,因为它会停止我程序中的所有内容,我只想让 runnable 暂停。
这里是延迟 2 秒的例子Runnable
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
// Do stuff
handler.postDelayed(this, 2000);
}
};
handler.postDelayed(runnable, 2000);
希望对您有所帮助
Handler handler = new Handler();
final Runnable runner = new Runnable()
{
public void run()
{
//Restarts
handler.postDelayed(this, 1000);
}
};
Thread thread = new Thread()
{
@Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(runner);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
听起来在你的例子中主线程被阻塞了。请参见下面的示例。这里主线程没有被wait阻塞。
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
try {
synchronized (this) {
wait(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
看这里是线程的例子:
Android.com / processes and threads
我希望我的 runnable 在重新开始之前等待几秒钟,关于如何做到这一点有什么建议吗?
如果我使用 this.wait();它不起作用,因为它会停止我程序中的所有内容,我只想让 runnable 暂停。
这里是延迟 2 秒的例子Runnable
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
// Do stuff
handler.postDelayed(this, 2000);
}
};
handler.postDelayed(runnable, 2000);
希望对您有所帮助
Handler handler = new Handler();
final Runnable runner = new Runnable()
{
public void run()
{
//Restarts
handler.postDelayed(this, 1000);
}
};
Thread thread = new Thread()
{
@Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(runner);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
听起来在你的例子中主线程被阻塞了。请参见下面的示例。这里主线程没有被wait阻塞。
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
try {
synchronized (this) {
wait(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
看这里是线程的例子: Android.com / processes and threads