java两个线程怎么让第一个线程停
时间: 2023-12-29 18:54:21 浏览: 27
可以使用线程间通信的方法来实现第一个线程停止的功能,例如使用共享变量来控制第一个线程的执行。
具体实现可以参考以下代码:
```java
public class ThreadStopDemo {
public static void main(String[] args) throws InterruptedException {
// 创建共享变量
AtomicBoolean stop = new AtomicBoolean(false);
// 创建第一个线程
Thread thread1 = new Thread(() -> {
while (!stop.get()) {
// 线程1执行的逻辑
System.out.println("Thread 1 is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread 1 stopped.");
});
// 创建第二个线程,用于停止第一个线程
Thread thread2 = new Thread(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 停止第一个线程
stop.set(true);
System.out.println("Thread 1 will be stopped.");
});
// 启动两个线程
thread1.start();
thread2.start();
// 等待第一个线程执行完毕
thread1.join();
}
}
```
在上述代码中,第一个线程会不断地执行逻辑,直到共享变量 `stop` 被设置为 `true`,第二个线程会在启动后等待 5 秒钟后将 `stop` 设置为 `true`,从而停止第一个线程。主线程通过 `join()` 方法等待第一个线程执行完毕后再退出。