要让一个线程总是先停止或先结束,可以通过以下几种方式实现:
示例代码:
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
// 线程1的逻辑
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
// 线程2的逻辑
}
});
thread1.start();
thread1.join(); // 等待线程1执行完毕
thread2.start();
示例代码:
class MyRunnable implements Runnable {
private volatile boolean flag = false;
@Override
public void run() {
while (!flag) {
// 线程的逻辑
}
}
public void stop() {
flag = true;
}
}
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
// 先停止线程1
runnable.stop();
示例代码:
class MyRunnable implements Runnable {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private boolean flag = false;
@Override
public void run() {
lock.lock();
try {
while (!flag) {
condition.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void stop() {
lock.lock();
try {
flag = true;
condition.signal();
} finally {
lock.unlock();
}
}
}
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
// 先停止线程1
runnable.stop();
以上是三种常见的方法,可以让一个线程总是先停止或先结束。具体选择哪种方法取决于实际需求和场景。
领取专属 10元无门槛券
手把手带您无忧上云