我想让线程B稍后结束,以便结果总是在结尾显示B9。我怎样才能做到这一点?这是我的代码。
package thread;
import java.lang.*;
import java.lang.Thread;
import java.lang.Runnable;
class Numprintt implements Runnable {
String myName;
public Numprintt(String name) {
myName = name;
}
public void run() {
for(int i = 0; i < 10; i++) {
System.out.print(myName + i + " ");
}
}
}
public class MyRunnableTest {
public static void main(String[] ar) {
Numprintt A = new Numprintt("A");
Numprintt B = new Numprintt("B");
Thread t1 = new Thread(A);
Thread t2 = new Thread(B);
t1.start();
t2.start();
try {
t1.join(); t2.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
我的结果可能会显示A1,A2,B1,....,B9 要么, B1,B2,A1,A2,...,A9 我希望结果总是像前一个一样显示。
答案 0 :(得分:3)
您可以利用- include_vars: "/etc/ansible/project/{{ some_env }}/vars.yml"
的功能。 CountDownLatch
使您能够等待从其他线程到同一CountDownLatch
对象的倒计时。这是您的问题的基本解决方案。
CountDownLatch
答案 1 :(得分:0)
public class MyRunnableTest {
public static void main(String[] ar) {
Numprintt A = new Numprintt("A");
Numprintt B = new Numprintt("B");
Thread t1 = new Thread(A);
Thread t2 = new Thread(B);
t1.start();
try {
t1.join();
t2.start();
t2.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这将保证线程A将首先结束