在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(() -> {
// 异步任务完成后调用回调函数
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();
}
}
以上是几种常见的向异步线程传递信息的方式,具体使用哪种方式取决于具体的需求和场景。