日期:2014-05-20  浏览次数:20790 次

java socket可以线程同步吗


import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class ZhuFrame extends JFrame implements ActionListener{
JPanel title=new JPanel();
JLabel head=new JLabel();
JLabel user=new JLabel();
DefaultMutableTreeNode node1=new  DefaultMutableTreeNode("我的好友"); // 定义树结点
DefaultMutableTreeNode node2=new  DefaultMutableTreeNode("我  的  群"); // 定义树结点
DefaultMutableTreeNode node3=new  DefaultMutableTreeNode("在线用户"); // 定义树结点
JTextField searchjtf=new JTextField(15);
JButton searchjbt=new JButton("查  找");
JTree friendsjtr=new JTree(node1);
JTree myqun=new JTree(node2);
JTree searchonlinejtr=new JTree(node3);
JPanel showjpa=new JPanel(new BorderLayout());
JPanel showjpa1=new JPanel(new BorderLayout());
JPanel showjpa2=new JPanel(new BorderLayout());
Socket socket;
DataInputStream input;
DataInputStream din;
DataOutputStream output;
DataOutputStream dout;
String username;//用户学号
String name;//聊天对象的学号
String ip="";//聊天对象的IP
String port="";//聊天对象的端口
String localport="";
boolean pass=false;
Thread th;
private static Lock lock=new ReentrantLock();
public  ZhuFrame(String userName,Socket socket){
Dimension screen=getToolkit().getScreenSize();
this.username=userName;
this.socket=socket;
this.setSize(280, 530);
this.setTitle(username);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocation(screen.width/7*5,100);
this.setVisible(true);

th=new Thread(new SocketHandler(socket));
th.start();

try{
input=new DataInputStream(socket.getInputStream());
output=new DataOutputStream(socket.getOutputStream());
output.writeUTF("getfriends "+username);
String friends=input.readUTF();
String[] fri=friends.split("#");
for(String i:fri){
node1.add(new  DefaultMutableTreeNode(i));
}
output.writeUTF("getqun "+username);
String qun=input.readUTF();
String[] quna=qun.split("#");
for(String i:quna){
node2.add(new  DefaultMutableTreeNode(i));
}
output.writeUTF("searchonline");
String[] online=input.readUTF().split("[ ]");
int j=0;
for(int i=0;i<online.length/4;i++){
node3.add(new DefaultMutableTreeNode(online[j]));
j+=4;
}
}catch(Exception e){
e.printStackTrace();
}

myqun.setRootVisible(true);
friendsjtr.setRootVisible(true);
searchonlinejtr.setRootVisible(true);
title.add(head);
title.add(user);
title.add(searchjtf);
title.add(searchjbt);
showjpa.add(friendsjtr,BorderLayout.NORTH);
showjpa.add(showjpa1,BorderLayout.CENTER);
showjpa1.add(myqun,BorderLayout.NORTH);
showjpa1.add(showjpa2,BorderLayout.CENTER);
showjpa2.add(searchonlinejtr,BorderLayout.NORTH);
showjpa2.setBackground(Color.WHITE);
showjpa.setBackground(Color.WHITE);