gpt4 book ai didi

Java线程,我怎样才能让一个线程总是先停止或结束?

转载 作者:行者123 更新时间:2023-11-29 04:23:19 25 4
gpt4 key购买 nike

我想让一个线程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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com