gpt4 book ai didi

java - 组合两个 Runnable 对象

转载 作者:行者123 更新时间:2023-12-02 21:58:16 26 4
gpt4 key购买 nike

例如,我有一个名为 RunnableA 的 Runnable,它可以执行某些操作。我还有一个名为 RunnableB 的 Runnable,它可以执行其他操作。有没有办法可以将这两个 Runnable 组合起来,以便它们在同一个线程中运行?

问题的第二部分是如果这可能的话,我可以指定它们运行的​​顺序吗?

编辑!:我想这样做的原因是因为我需要在 EDT 上运行代码,但其他一些代码需要在另一个线程上运行。请看一下下面的代码。

类似这样的事情


public final class CompoundRunnable implements Runnable
{
private final Iterable runnables;

public CompoundRunnable(Iterable runnables)
{
// From Guava. Easy enough to do by hand if necessary
this.runnables = Lists.newArrayList(runnables);

}

public CompoundRunnable(Runnable... runnables)
{
this(Arrays.asList(runnables));
}

@Override
public void run()
{
for (Runnable runnable : runnables)
{
runnable.run();
}
}
}

public void setStatusAndProgress(final String status,Runnable runnable)
{
Runnable startUpRunner = new Runnable()
{
public void run()
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
setStatus(status);
selfReference.getProgressBar().setIndeterminate(true);
}

});
}
};
Runnable cleanUpRunner = new Runnable()
{
public void run()
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
setStatus("");
getProgressBar().setIndeterminate(false);
}
});
}
};

Runnable theRunner = new CompoundRunnable(startUpRunner,runnable,cleanUpRunner);
new Thread(theRunner).start();
}

抱歉,如果这没有得到很好的解释,如果您需要澄清,请发表评论。

谢谢!

最佳答案

那么你当然可以创建一个 Runnable它只运行一个可运行程序,然后运行另一个:

public final class CompoundRunnable implements Runnable
{
private final Runnable first;
private final Runnable second;

public CompoundRunnable(Runnable first, Runnable second)
{
this.first = first;
this.second = second;
}

@Override
public void run()
{
first.run();
second.run();
}
}

更一般地说,您可以将其设置为 Iterable<Runnable> ,复制所有Runnable引用,然后按顺序运行它们。例如:

public final class CompoundRunnable implements Runnable
{
private final Iterable<Runnable> runnables;

public CompoundRunnable(Iterable<Runnable> runnables)
{
// From Guava. Easy enough to do by hand if necessary
this.runnables = Lists.newArrayList(runnables);
}

public CompoundRunnable(Runnable... runnables)
{
this(Arrays.asList(runnables));
}

@Override
public void run()
{
for (Runnable runnable : runnables)
{
runnable.run();
}
}
}

关于java - 组合两个 Runnable 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661983/

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