[英]Need to split a thread so it runs in multiple threads. Also need to figure out a synchronized issue - JAVA
该程序旨在显示网络中最老,最年轻的人。
我需要弄清楚如何改进它,所以我没有得到ConcurrentModificationException。 当我要求多次显示更多信息时,例如要求最年轻,最老的人,并使其刷新以告诉我谁是当前最年轻的人时,就会得到此信息。
public void randomIncreaseCoupling(int amount, double chance, double inverseChance) {
randomChangeCoupling(amount,chance,inverseChance,true);
}
public void randomDecreaseCoupling(int amount, double chance, double inverseChance) {
randomChangeCoupling(amount,chance,inverseChance,false);
该代码在网络中用于随机更改日期结果。
另外,我目前正在线程中运行此函数,但是我需要将其紧固,因此需要运行每个“功能”以在各自的线程中运行。
MainController类通过以下方式启动线程:
public void startEvolution() {
if (display == null)
throw new Error("Controller not initialized before start");
evolutionThread = new NetworkEvolutionSimulator(network, display);
evolutionThread.start();
}
当我单击任意按钮,然后单击某个按钮以向我显示该网络中最古老的按钮时,可通过以下方式完成:
public void startOldest() {
if (display == null)
throw new Error("Not properly initialized");
int order = display.getDistanceFor(Identifier.OLDEST);
Set<Person> oldest = network.applyPredicate(PredicateFactory.IS_OLDEST,
order);
display.displayData(Identifier.OLDEST, summarize(order, oldest));
我试图使它像:
public void startOldest() {
if (display == null)
throw new Error("Not properly initialized");
int order = display.getDistanceFor(Identifier.OLDEST);
Set<Person> oldest = network.applyPredicate(PredicateFactory.IS_OLDEST,
order);
display.displayData(Identifier.OLDEST, summarize(order, oldest));
evolutionThread2 = new NetworkEvolutionSimulator(network, display);
evolutionThread2.start();
但这会在我按下按钮时一遍又一遍地启动主线程。 我想要的是此特定功能以及其他功能,当我按下cercain按钮时,必须在各自的线程中启动每个功能,这样我一次就能使用多个功能。 我该怎么办?
如果需要,我可以解释更多。
提前致谢。 我的第一篇文章,很抱歉,如果我没有遵循特定的规则。
您可以使用synced关键字-
synced关键字可用于标记几种类型的代码块:
您在使用oldest
设置的任何地方都可以添加一个这样的synchronized
代码块
synchronized(oldest) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.