gpt4 book ai didi

java - 让线程只是等待

转载 作者:行者123 更新时间:2023-12-01 07:36:49 25 4
gpt4 key购买 nike

请告诉我如何让线程等待。例如,如果 i == 0 则等待,当 i == 1

时再次进行
public class Main {

public Main() {
}

public void method() {

Thread thread = new Thread(new Task());
// I want to make wait it when I want
// for example wait if i == 0 and go again when i = 1
}

public static void main(String[] args) {
new Main();
}
}

最佳答案

这适用于 CountDownLatch .

    public static void main( String[] args ) throws Exception {
final CountDownLatch latch = new CountDownLatch( 1 );
System.out.println( "Starting main thread" );
new Thread( new Runnable() {
public void run() {
System.out.println( "Starting second thread" );
System.out.println( "Waiting in second thread" );
try {
latch.await();
} catch ( InterruptedException e ) {
e.printStackTrace();
}
System.out.println( "Stopping second thread" );
}
} ).start();

Thread.sleep( 5000 );
System.out.println( "Countdown in main thread" );
latch.countDown();

Thread.sleep( 1000 );
System.out.println( "Stopping main thread" );
}

关于java - 让线程只是等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10869242/

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