【发布时间】:2015-01-26 17:26:08
【问题描述】:
每次单击按钮时都会调用此代码
//Thread called when click a button
Thread a = new Thread(new Runnable() {
@Override
public void run() {
synchronized ((Object) contadordeMierda){
Random rn = new Random();
int n= rn.nextInt(10) + 1;
contador++;
try {
Thread.sleep(n*100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(contador);
}
}
});
a.start();
当我快速触摸它几次时,我得到了这个输出:
I/System.out﹕1
I/System.out﹕2
I/System.out﹕5
I/System.out﹕5
I/System.out﹕9
I/System.out﹕9
I/System.out﹕9
I/System.out﹕9
I/System.out﹕9
...
如何等待一个线程完成来启动另一个线程?所以打印出来 1 2 3 4 5 6 7 8 9 10 11 12...?
【问题讨论】:
-
我不太确定 android,但我很难相信按钮点击是异步处理的,所以我怀疑线程没有以正确的顺序启动,但是相反,不能保证它们的执行顺序。使用带有单个支持线程或类似线程的 ExecutorService 可能会更好。 docs.oracle.com/javase/7/docs/api/java/util/concurrent/…
-
你在哪里以及如何声明你的锁
contadordeMierda? -
inside run(){ synchronized ((Object) contadordeMierda){...如果我不转换为 Object 它会显示错误
-
您是否在按钮的 OnClickListerner 中声明了
contadordeMierda?
标签: java android multithreading wait synchronize