在Java中,可以使用以下幾種方式向異步線程傳遞信息:
例如:
public class Main {
private static String message;
public static void main(String[] args) throws InterruptedException {
Thread asyncThread = new Thread(() -> {
while (message == null) {
// 等待主線程寫入信息
}
System.out.println("異步線程接收到信息:" + message);
});
asyncThread.start();
// 主線程寫入信息
message = "Hello World";
asyncThread.join();
}
}
例如:
public class Main {
public interface Callback {
void onCompleted(String message);
}
public static void main(String[] args) throws InterruptedException {
Thread asyncThread = new Thread(() -> {
// 異步任務(wù)完成后調(diào)用回調(diào)函數(shù)
String message = "Hello World";
callback.onCompleted(message);
});
asyncThread.start();
asyncThread.join();
}
}
例如:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private static String message;
private static final Lock lock = new ReentrantLock();
private static final Condition condition = lock.newCondition();
public static void main(String[] args) throws InterruptedException {
Thread asyncThread = new Thread(() -> {
lock.lock();
try {
while (message == null) {
// 等待主線程寫入信息
condition.await();
}
System.out.println("異步線程接收到信息:" + message);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
});
asyncThread.start();
// 主線程寫入信息
lock.lock();
try {
message = "Hello World";
condition.signal();
} finally {
lock.unlock();
}
asyncThread.join();
}
}
以上是幾種常見的向異步線程傳遞信息的方式,具體使用哪種方式取決于具體的需求和場(chǎng)景。