线程操作问题
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
public class chatServer {
/**
* @param args
*/
private ServerSocket ss=null;
private Socket s=null;
private boolean Started=true;
private List <Clint> Clints=new ArrayList <Clint> ();
public static void main(String[] args) {
new chatServer();
}
public chatServer()
{
boolean Started=true;
try {
ss=new ServerSocket(6666);
while(Started)
{
s=ss.accept();
Clint c=new Clint(s);
Clints.add(c);
Thread t=new Thread(c);
t.start();
}
//用线程实现以上方法
System.out.println( "我跳出来了 ");
} catch (
IOException e) {
e.printStackTrace();
}
}
class Clint implements Runnable{
Socket s;
DataInputStream dis;
DataOutputStream dos;
public void run() {
}
public Clint(Socket s)
{
this.s=s;
try {
dis=new DataInputStream(s.getInputStream());
String str=dis.readUTF();
if(str.equals( "bye "))
{
System.out.println( "和服务器断开连接 ");
Started=false;
dis.close();
s.close();
}
else
{
System.out.println(str);
}
System.out.println(Started);
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str)
{
try {
dos.writeUTF(str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
用一个客户端给服务端发信息,然后服务端打印。当客户端输入bye是是服务端停止,以上是服务端的代码,我再内部类中操作外部类的一个变量,为什么再内部类中可以看到值已经变了,开始外部类的循环还在继续,也就是我输入数据后服务器还会打印
下面是客户端的代码
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.Border;
import sun.awt.WindowClosingListener;
public class chatClint extends Frame {
/**
* @param args
*/
private Socket s=null;
private TextArea ta=null;
private TextField tf=null;
public static void main(String[] args) {
new chatClint();
}
public chatClint()
{
this.setLocation(100,100);
this.setSize(400,300);
this.setVisible(true);
ta=new TextArea();
tf=new TextField();
tf.addActionListener(new Post());
add(ta,BorderLayout.NORTH);
add(tf,BorderLayout.SOUTH);
pack();
setVisible(true);
this.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e) {
System.exit(1);
}
});
}
class Post implements ActionListener
{
public void actionPerformed(ActionEvent e) {