当前位置:编程学习 > JAVA >>

Server端的多线程的运用

想要运行多个线程,就将想要同步运行的代码加到另一个实现Runnable接口的类中,在主类的一个方法中实例化这个类的对象将他传给另一个类Thread,在主类的主线程中调用这个方法,即可实现线程同步
01 import java.net.*;
02 import java.io.*;
03 
04 public class ChatServer {
05     boolean started = false;
06     Socket s = null;
07     ServerSocket ss = null;
08     public static void main(String[] args) {
09     new ChatServer().start();
10     }
11 public void start(){
12     try {
13     ss = new ServerSocket(8888);
14     started = true;
15 } catch (IOException e) {
16     System.out.println("some Exception on program");
17 }
18 try {
19     while (started) {
20         boolean connect = false;
21         s = ss.accept();
22         System.out.println("A Client Connect");
23         Client c=new Client(s);
24         new Thread(c).start();
25     }
26 } catch(IOException e){
27     System.out.println("连接出错");
28     System.exit(0);
29 }
30     
31 }
32 class Client implements Runnable{
33     private Socket s=null;
34     private DataInputStream dis=null;
35     private boolean connect=false;
36     public Client(Socket s){
37         this.s=s;
38         try {
39             dis=new DataInputStream(s.getInputStream());
40         } catch (IOException e) {
41             e.printStackTrace();
42         }
43     }
44     public void run(){
45         connect = true;
46         while (connect) {
47             try {
48                 System.out.println(dis.readUTF());
49             } catch (IOException e) {
50                 System.out.println("some exception on the program");
51                 System.exit(0);www.zzzyk.com
52 
53             } finally {
54                 try {
55                     if (dis == null)
56                         dis.close();
57                     if (s == null)
58                         s.close();
59                 } catch (IOException e) {
60                     System.out.println("some exception on program");
61                     System.exit(0);
62                 }
63             }
64         }
65     }
66 }
67 }

 作者:Seaer

补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,