【发布时间】:2013-04-18 04:49:25
【问题描述】:
我有使用多线程将对象发送到 ServerSocket 的代码(目前在本地,但将来在本地网络中)
用于发送对象:
public class SocketToAdapter {
public static void writeObject(Object object) {
try {
give().writeUnshared(object);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
static ObjectOutputStream give() {
Socket s = null;
try {
s = new Socket("localhost", 9990);
s.setTcpNoDelay(true);
return new ObjectOutputStream(s.getOutputStream());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
主要方法:
SocketToAdapter soc = new SocketToAdapter();
thread1.setSocket(soc);
thread2.setSocket(soc);
thread3.setSocket(soc);
thread4.setSocket(soc);
thread5.setSocket(soc);
synchronized (valueExchanging) {
synchronized (soc) {
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
valueExchang 是一个对象,用于在线程之间交换数据。
从线程运行方法:
public void run() {
try {
while (true) {
curr = new Object(pair, RandomUtil.getRandomExchange(),
RandomUtil.getRandomTurn());
//not important Business Logic.
int v1 = valueExchanger.getExchangeInTread()+1;
int v2 = valueExchanger.getExchangeInTread()-100;
curr = new Object(pair, BigInteger.valueOf(v1),
BigInteger.valueOf(v2));
//
SocketToAdapter.writeObject(curr);
valueExchanger.setExchangeInTread(v1);
Thread.sleep(0, 1);
}
} catch (InterruptedException iex) {
}
}
这行得通,但速度很慢。可能是因为我每次需要时都会创建 Socket 和 ObjectOutputStream 。我尝试创建一个 Socket 和一个 OOS 并像这样使用它:
{
Socket s = new Socket("localhost", 9990);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); }
然后
oos.writeUnshared(object);
oos.flush();
oos.writeUnshared(object);
但是如果我第二次尝试重用 oos,我得到软件导致连接中止:套接字写入错误。不管我使用多少线程。
我需要的是每秒发送许多(例如 100k)对象的可能性,有什么建议吗?
在服务器端我做:
Serwer.java:
ServerSocket ss;
public static void pre()throws IOException, ClassNotFoundException {
ss = new ServerSocket(9990);
}
public static Object start() throws IOException, ClassNotFoundException {
Object o = null;
Socket s = ss.accept();
while (!s.isClosed()) {
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
o = (Object) ois.readObject();
ois.close();
s.close();
}
ss.close();
return o;
}
“主要方法”
while (true) {
try {
Serwer.pre();
Object o = Serwer.start();
//im do somethink with that object o.
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
【问题讨论】:
-
启动线程时为什么要在soc上同步?当使用来自多个线程的资源时,您必须在资源上进行同步。并保持同步块简短。或者甚至尝试在没有的情况下相处。同步是一个巨大的性能杀手。
-
目前同步不是问题(即使我使用一个没有同步的线程,性能很差)。
-
你必须为你的设计带来更多的结构。无意冒犯,但尽量不要在一个地方做太多事情......
标签: java sockets serversocket objectoutputstream