gpt4 book ai didi

java - 是否可以挂起子线程然后回调父线程,然后再次恢复子线程

转载 作者:行者123 更新时间:2023-11-30 02:03:23 26 4
gpt4 key购买 nike

我的 JAVA 代码正在创建一个扩展线程类的类

   public static void main(String[] args)
{
MyThread ct=new MyThread();
Thread t=new Thread(ct);
t.start();
System.out.println(5);
}

public class MyThread extends Thread {
public void run()
{
for(int i=1;i<=10;i++)
{ System.out.println("abc");
if (i==5)
//do something


}

输出应该是:-ABCABCABCABC5ABCABCABCabc

最佳答案

要得到想要的输出,不仅需要在i == 5时暂停子线程,还需要暂停主线程,直到子线程打印出前五个abc.

您可以使用两个 CountDownLatch用于子线程和主线程之间的通信:

import java.util.concurrent.CountDownLatch;

public class Main {


static class Child implements Runnable {

CountDownLatch waitLatch;
CountDownLatch notifyLatch;

public Child(CountDownLatch waitLatch, CountDownLatch notifyLatch) {
this.waitLatch = waitLatch;
this.notifyLatch = notifyLatch;
}

@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("abc");
if (i == 5) {
try {
notifyLatch.countDown(); // signal main thread, let it print number 5
waitLatch.await(); // wait for the signal from main thread
} catch (InterruptedException e) {

}
}
}
}
}

public static void main(String[] args) {

CountDownLatch waitLatch = new CountDownLatch(1);
CountDownLatch notifyLatch = new CountDownLatch(1);

Runnable child = new Child(waitLatch, notifyLatch);
new Thread(child).start();

try {
notifyLatch.await(); // wait for the signal from child thread
} catch (InterruptedException ignore) {

}
System.out.println(5);
waitLatch.countDown(); // resume child thread
}
}

关于java - 是否可以挂起子线程然后回调父线程,然后再次恢复子线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52099642/

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