我有两个线程 A 和 B。如果 A 线程先完成,我需要执行函数1;如果 B 线程先完成,我需要执行函数2。我如何知道哪一个线程先完成了执行?
我有两个线程 A 和 B。如果 A 线程先完成,我需要执行函数1;如果 B 线程先完成,我需要执行函数2。我如何知道哪一个线程先完成了执行?
您可以使用以下代码,它只会在前一个值为null时才被设置。(即使只有一个线程,也可以使用此方法来确保值在设置后不会更改)
AtomicReference<ValueType> ref = new AtomicReference<ValueType>();
ref.compareAndSet(null, value);
import java.util.concurrent.Semaphore;
public class ThreadTest {
private Semaphore semaphore = new Semaphore(0);
private String winner;
private synchronized void finished(String threadName) {
if (winner == null) {
winner = threadName;
}
semaphore.release();
}
public void run() {
Runnable r1 = new Runnable() {
public void run() {
try {
Thread.sleep((long) (5000 * Math.random()));
}
catch (InterruptedException e) {
// ignore
}
finally {
finished("thread 1");
}
}
};
Runnable r2 = new Runnable() {
public void run() {
try {
Thread.sleep((long) (5000 * Math.random()));
}
catch (InterruptedException e) {
// ignore
}
finally {
finished("thread 2");
}
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
try {
semaphore.acquire();
System.out.println("The winner is " + winner);
}
catch (InterruptedException e) {
System.out.println("No winner");
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
new ThreadTest().run();
}
}
import java.util.concurrent.CountDownLatch;
public class ThreadTest {
private CountDownLatch latch = new CountDownLatch(1);
private String winner;
private synchronized void finished(String threadName) {
if (winner == null) {
winner = threadName;
}
latch.countDown();
}
public void run() {
Runnable r1 = new Runnable() {
public void run() {
try {
Thread.sleep((long) (5000 * Math.random()));
}
catch (InterruptedException e) {
// ignore
}
finally {
finished("thread 1");
}
}
};
Runnable r2 = new Runnable() {
public void run() {
try {
Thread.sleep((long) (5000 * Math.random()));
}
catch (InterruptedException e) {
// ignore
}
finally {
finished("thread 2");
}
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
try {
latch.await();
System.out.println("The winner is " + winner);
}
catch (InterruptedException e) {
System.out.println("No winner");
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
new ThreadTest().run();
}
}
如果你想在展示获胜者之前等待两个线程完成,你只需要将门闩的初始值从1改为2。
许多解决方案之一是,有一个共享的标志变量。
import java.util.concurrent.atomic.AtomicInteger;
final AtomicInteger winner = new AtomicInteger(0);
然后在第一个线程的run()方法调用结束时
winner.compareAndSet(0, 1);
winner.compareAndSet(0, 2);
winner.get()