📄 receivethread.java
字号:
package com.jim.client;
import java.util.Date;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import com.jim.database.JIMUser;
import com.jim.net.Connection;
import com.jim.net.JIMProtocol;
import com.jim.net.Message;
public class ReceiveThread extends Thread {
/**
* 负责日志处理
*/
private Logger log = Logger.getLogger(this.getClass());
/**
* 一个用于控制线程结束的标记
*/
private volatile Thread blinker;
/**
* 控制线程是否阻塞
*/
private volatile boolean threadSuspended = false;
/**
* 客户端到服务器的连接。
*/
private Connection connection;
private boolean block;
private MainWin mainWin;
/**
* 使用一个Connection对象来构造该线程。
*/
public ReceiveThread (Connection con ,MainWin win){
this.connection = con;
this.mainWin = win;
setName("Receiving thread");
}
/**
* 该线程要执行的代码。
*/
public void run(){
//用于控制线程的结束。
Thread thisThread = Thread.currentThread();
blinker = thisThread;
int cmd = 0;
//没有指示线程结束时,不断的循环
while(blinker == thisThread){
try{
//如果连接正在被使用,则等待一段时间后继续。
if(connection.isBusy()){
log.debug("waiting connection to receive message");
thisThread.sleep(200);
continue;
}else if(connection.isAvialable()){
//否则就读取服务器发送来的只是命令。
log.debug("receive thread: block on read command");
block = true;
cmd = connection.getCommand();
log.debug("receive thread: get a command:"+cmd);
block = false;
}
else
continue;
//当指示的命令为接收消息时,就读取一个Message对象。
if(cmd == JIMProtocol.GETMSG){
connection.setBusy(true);
Message msg =(Message)connection.receive();
connection.setBusy(false);
//处理这个Message。
log.debug("get a message");
mainWin.processMsg(msg);
msg = null;
}
}catch(InterruptedException e){
e.printStackTrace();
finish();
}
}
}
/**
* 要结束该线程
*/
public void finish() {
Thread moribund = blinker;
blinker = null;
if(moribund != null)
moribund.interrupt();
}
public void unSuspend(){
threadSuspended = false;
//@TODO 这里可能有问题的。
//notify();
}
public synchronized boolean isBlock() {
return block;
}
public synchronized MainWin getMainWin() {
return mainWin;
}
public synchronized void setMainWin(MainWin mainWin) {
this.mainWin = mainWin;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -