心中已经得到了其使用多线程发送对象ServerSocket的代码(目前localy,但在本地网络的未来)Java的插座ObjectOutputStream的多线程
用于发送对象:
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();
}
valueExchanging是用于beetwen线程交换数据的对象。
从线程运行方法:
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)对象每秒,任何sugesstions?
在服务器端我做的:
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?当使用来自多个线程的资源时,您必须在资源上进行同步。并保持同步块的简短。甚至不尝试相处。同步是一个巨大的性能杀手。 – Fildor 2013-04-24 15:07:21
目前不是同步问题(即使我使用一个没有同步的线程,性能很糟糕)。 – user1055201 2013-04-24 15:12:46
你一定要为你的设计带来更多的结构。没有冒犯,但尽量不要在一个地方做太多事情...... – Fildor 2013-04-24 17:12:42