首先,我是线程和共享变量的新手。所以请善待我;-)
我有一堂课叫Routing
. 这个类接收和处理消息。如果消息属于类型A
,则Routing
-Object 应将其传递给ASender
实现Runnable
接口的对象。如果消息是类型B
,则Routing
-Class 应将其传递给BSender
Object。
但是ASender
和BSender
对象有共同的变量,应该存储到Routing
-Object 中。
我现在的想法是在Routing
-Object 和 getter/setter 中将变量声明为同步/易失性。
这是同步代码的正确方法吗?还是缺少什么?
编辑:添加了基本的代码思想。
路由类
public class Routing {
private synchronized Hashtable<Long, HashSet<String>> reverseLookup;
private ASender asender;
private BSender bsender;
public Routing() {
//Constructor work to be done here..
reverseLookup = new Hashtable<Long, HashSet<String>>();
}
public void notify(TopicEvent event) {
if (event.getMessage() instanceof AMessage) {
asender = new ASender(this, event.getMessage())
} else if (event.getMessage() instanceof BMessage) {
bsender = new BSender(this, event.getMessage())
}
}
public synchronized void setReverseLookup(long l, Hashset<String> set) {
reverseLookup.put(l, set);
}
public synchronized Hashtable<Long, Hashset<String>> getReverseLookup() {
return reverseLookup;
}
}
ASender 类
public class ASender implements Runnable {
private Routing routing;
private RoutingMessage routingMessage;
public ASender(Routing r, RoutingMessage rm) {
routing = r;
routingMessage = rm;
this.run();
}
public void run() {
handleMessage();
}
private void handleMessage() {
// do some stuff and extract data from the routing message object
routing.setReverseLookup(somethingToSet)
}
}