socket tcp编程发送线程不执行

import java.io.IOException;
import java.io.OutputStream;

public class MsgSender extends Thread {

    String content;
    OutputStream out;
    String name;
    private boolean isRunning;
    /**
     * 
     * @param out 从socket中返回的输出流
     * 
     */
    public MsgSender( OutputStream out){
        this.out = out;
        isRunning = true;
        this.content = "";
    }

    public void setMessage( String msg ){
        this.content = msg;
    }

    public void run(){

        while(isRunning){
        //当内容不为空时发送给客户端
            if(!content.isEmpty()){
                byte[] buff = content.getBytes();
                try {
                    out.write(buff);
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                content = "";
            }
            //但是没有下面这段代码,此线程会挂死
            //即使content不为空也不会执行循环里面的代码
            if(content.isEmpty()){
                try {
                    sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public void stopSelf(){
        isRunning = false;
    }

}

猜你喜欢

转载自blog.csdn.net/u012859430/article/details/54581486
今日推荐