我想让一个线程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 我希望结果始终像前一个一样显示。
最佳答案
您可以利用 CountDownLatch
的功能。 CountDownLatch
使您能够等待从其他线程到同一个 CountDownLatch
对象的倒计时。这是您的问题的基本解决方案。
import java.lang.*;
import java.lang.Thread;
import java.lang.Runnable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
class Numprintt implements Runnable {
private final CountDownLatch latch;
private String myName;
public Numprintt(String name, CountDownLatch latch) {
this.myName = name;
this.latch = latch;
}
public void run() {
for (int i = 0; i < 10; i++) {
if (i == 9 && latch != null) {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(myName + i + " ");
}
}
}
public class MyRunnableTest {
public static void main(String[] ar) {
CountDownLatch latch = new CountDownLatch(1);
Numprintt A = new Numprintt("A", null);
Numprintt B = new Numprintt("B", latch);
Thread t1 = new Thread(A);
Thread t2 = new Thread(B);
t1.start();
t2.start();
try {
t1.join();
latch.countDown();
t2.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
关于Java线程,我怎样才能让一个线程总是先停止或结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47786172/