java 在一个线程类中执行另一个线程类,并控制另一个线程类的执行和暂停
时间: 2024-04-13 07:28:46 浏览: 27
在Java中,你可以使用Thread类来执行另一个线程,并通过一些机制来控制它的执行和暂停。以下是一个示例代码,演示如何在一个线程类中执行另一个线程类,并控制其执行和暂停:
```java
class WorkerThread implements Runnable {
private Thread thread;
private boolean isPaused;
public WorkerThread() {
thread = new Thread(this);
isPaused = false;
}
public void start() {
thread.start();
}
public void pause() {
isPaused = true;
}
public void resume() {
isPaused = false;
synchronized (this) {
notify();
}
}
@Override
public void run() {
while (true) {
if (isPaused) {
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 执行你想要在另一个线程中执行的任务
System.out.println("Executing task...");
try {
Thread.sleep(1000); // 模拟任务执行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
WorkerThread workerThread = new WorkerThread();
workerThread.start();
Thread.sleep(5000); // 等待5秒钟
workerThread.pause();
Thread.sleep(5000); // 等待5秒钟
workerThread.resume();
}
}
```
在上面的示例中,`WorkerThread`是一个实现了`Runnable`接口的线程类。它有一个`isPaused`变量来控制线程的执行和暂停。在`run()`方法中,通过检查`isPaused`变量来决定是否执行任务。如果线程被暂停,它会进入等待状态,直到`resume()`方法被调用。
在`Main`类中,我们创建了一个`WorkerThread`实例,并调用`start()`方法来启动线程。然后,我们使用`Thread.sleep()`方法来等待一段时间,然后调用`pause()`方法来暂停线程的执行。再次等待一段时间后,我们调用`resume()`方法来恢复线程的执行。
这样,我们就可以在一个线程类中执行另一个线程类,并通过控制方法来控制其执行和暂停。请注意,在实际使用中,你可能需要更多的同步机制来确保线程安全性。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)