每次单击按钮
时都会调用此代码 //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 ......?
答案 0 :(得分:1)
这是join() function的确切目的。很多次问过问题:How to wait for a number of threads to complete?。
答案 1 :(得分:-1)
为什么不这样做:只有当前没有线程运行时才启动新线程:
private boolean isThreadRunning = false;//declare a boolean field to store thread status whether it's running or not
...
if(!isThreadRunning){
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);
isThreadRunning = false;//Set the boolean variable to false because the thread has completed it's operations.
}
}
});
a.start();
isThreadRunning = true;// Set the boolean to true because thread.start has been called.
}