心中已經得到了其使用多線程發送對象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