在Java中不使用线程,让某个函数暂停
时间: 2024-03-03 11:49:19 浏览: 22
在Java中,可以使用`Thread.sleep()`方法来让当前线程暂停一段时间。但是如果你不想使用线程,可以使用`java.util.concurrent.CountDownLatch`类来实现。
`CountDownLatch`类是一个同步辅助类,它允许一个或多个线程等待直到在其他线程中执行的一组操作完成。
下面是一个例子,展示了如何使用`CountDownLatch`类来实现函数暂停:
```
import java.util.concurrent.CountDownLatch;
public class FunctionPauseExample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
System.out.println("Function starting...");
doSomething(latch);
System.out.println("Function paused...");
// Wait for the latch to be released by another thread
latch.await();
System.out.println("Function resumed...");
doSomethingElse();
}
private static void doSomething(CountDownLatch latch) {
new Thread(() -> {
// Do some work here...
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Release the latch to signal that the work is done
latch.countDown();
}).start();
}
private static void doSomethingElse() {
System.out.println("Doing something else...");
}
}
```
在该例子中,`doSomething()`方法是一个耗时的操作,它会启动一个新的线程来执行任务。当任务完成后,它会释放`CountDownLatch`对象,通知主线程可以继续执行。主线程在调用`doSomething()`方法后暂停执行,等待`CountDownLatch`对象被释放。一旦释放,主线程就可以继续执行`doSomethingElse()`方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)