gpt4 book ai didi

Java - 使用另一个类的静态列表

转载 作者:行者123 更新时间:2023-11-30 04:15:20 25 4
gpt4 key购买 nike

我有一个这样的类,我在其中更新线程中的静态变量。我需要从另一个类访问这个变量。

import java.util.ArrayList;
import java.util.List;

public class VariableUpdater implements Runnable {
static List < String > abc = new ArrayList < String > ();

private static VariableUpdater instance = null;

private VariableUpdater() {}

public static synchronized VariableUpdater getInstance() {
if (instance == null) {
instance = new VariableUpdater();
}
return instance;
}

public static void main(String[] args) {
Thread th = new Thread( VariableUpdater.getInstance());
th.start();
}

@Override
public void run() {
while (true) {
System.out.println();
try {
abc.add("aa");
Thread.sleep(1000);
printContent();
} catch (Exception e) {
// TODO: handle exception
}

}

}

public synchronized void printContent() {
for (String string: abc) {
System.out.println(string);
}
}
}

这个变量需要从另一个类访问,如下所示:

public class Accessor {
public static void main(String[] args) {
VariableUpdater.getInstance().printContent();
}
}

问题是,当运行 Accessor 类时,列表为空。

我在这里遗漏了什么吗?

更新/解决方案

事实证明,我们可以通过使用 Hazelcast 或某种消息传递/缓存实用程序来实现这一目标。我将很快发布完整的解决方案。

来源:How to share object between java applications?

最佳答案

通过此代码,您可以访问另一个类对象中的列表

import java.util.ArrayList;
import java.util.List;

public class VariableUpdater implements Runnable {
static List < String > abc = new ArrayList < String > ();

private static VariableUpdater instance = null;

private VariableUpdater() {}

public static synchronized VariableUpdater getInstance() {
if (instance == null) {
instance = new VariableUpdater();
}
return instance;
}

public static void main(String[] args) {
Thread th = new Thread(new VariableUpdater());
th.start();
Accessor.print();
}

@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println();
try {
abc.add("aa");
// Thread.sleep(1000);
//printContent();
} catch (Exception e) {
e.printStackTrace();
}

}

}

public synchronized void printContent() {
System.out.println("List :: " + abc);
}
}

class Accessor {
public static void print() {
System.out.println("Accessor");
VariableUpdater.getInstance().printContent();
}
}

关于Java - 使用另一个类的静态列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18548534/

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