gpt4 book ai didi

java - 如何大约同时运行两个操作?

转载 作者:行者123 更新时间:2023-11-29 03:00:43 25 4
gpt4 key购买 nike

我正在用 Java 构建测试工具,并尝试比较两个解析器的性能和延迟。解析来自实时单一提要的 munge 数据。我无法控制提要,也没有用于模拟数据的“模拟提要”,因此为了比较苹果与苹果,我想尽可能同时运行我的解析。我是 Java 和线程的新手,所以不确定这是否是最好的方法。我的想法是旋转 2 个线程:

SomeFeed feed = new SomeFeed();

Thread thread1 = new Thread () {
public void run () {
parser1.parseFeed(feed);
}
};
Thread thread2 = new Thread () {
public void run () {
parse2.parseFeed(feed);
}
};
thread1.start();
thread2.start();

以这种方式运行的线程会大致同步运行吗?或者有更好的方法吗?

谢谢

最佳答案

让两个线程完全并行运行并不是您真正可以控制的。但是如果你想同时启动它们(几乎)你可以使用CyclicBarrier (取自 here ):

// We want to start just 2 threads at the same time, but let's control that 
// timing from the main thread. That's why we have 3 "parties" instead of 2.
final CyclicBarrier gate = new CyclicBarrier(3);

Thread t1 = new Thread(){
public void run(){
gate.await();
//do stuff
}};
Thread t2 = new Thread(){
public void run(){
gate.await();
//do stuff
}};

t1.start();
t2.start();

// At this point, t1 and t2 are blocking on the gate.
// Since we gave "3" as the argument, gate is not opened yet.
// Now if we block on the gate from the main thread, it will open
// and all threads will start to do stuff!

gate.await();
System.out.println("all threads started");

这将使您最接近于同时启动它们。

关于java - 如何大约同时运行两个操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35184455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com