1. 所谓内部类,就是类中之类, 也就是无论我们是通过继承Thread类来开线程,还是通过实现Runnable接口来开 线程,这个线程类即可以写在 主类之外,也可以写在主类之内。不多说, 直接看代码就明白了。
public class ChatServerData {
public void start(){
try{
ss1 = new ServerSocket(6666);
}catch(BindException e){
System.out.println("端口使用中");
System.exit(0);
}catch(IOException e){
e.printStackTrace();
}
//上面的不重要,主要看下面这段代码的new Thread(c1).start(),以及线程类所在的位置(类内)
try{
started1 = true;
while(started1){
Socket s1 = ss1.accept();
Client1 c1 = new Client1(s1);
clients1.add(c1);
new Thread(c1).start();
}
}catch(IOException e){
}
finally{
try {
ss1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Client1 implements Runnable{
private boolean beconnected=false;
private Socket s;
private DataInputStream dis=null;
private DataOutputStream dos=null;
public Client1(Socket s){
this.s=s;
try {
dis=new DataInputStream(s.getInputStream());
dos=new DataOutputStream(s.getOutputStream());
beconnected=true;
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
}//这是线程类的最后一个括号
}//这是主类的最后一个括号
希望可以帮到你~~~~~