請教大俠。關於多執行緒同步問題

alvin841027發表於2010-09-16
小弟寫了一個程式。但是不知道怎麼能做成singleton 同步多執行緒的模式。請各位大俠賜教,謝謝



package kid;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.Calendar;

import entertainer.EntertainerIF;
import entertainer.KidId;
import entertainer.Message;

public class Kid {

private String kidname;
private String matchName;
private int localServerPort;
private ServerSocket servsock;
private EntertainerIF entertainer;
private Socket entertainersock;
private boolean gameover = false;
private KidId leftKid;
private KidId rightKid;
private Socket leftKidSock;
private Socket rightKidSock;
private boolean haveBaloon;

private Thread threadEntertainer;
private Thread threadLeftKid;
private Thread threadRightKid;
private Thread workingThread;

private int gameRound = 1;

public Kid() {
setThreadInfo();
}

private void setThreadInfo() {
// create reading socket thread
if (threadEntertainer == null) {
threadEntertainer = new Thread() {

@Override
public void run() {
boolean stop = false;
while (!gameover && !stop) {
try {
if (entertainersock != null) {
// System.out.println("Reading socket from entertainersock.....");
readMsg(entertainersock);
}
sleep(100);
//不能使用thread。sleep的方法
} catch (SocketException se) {
if (entertainersock.isClosed()) {
System.out
.println("entertainersock is closed.");
entertainersock = null;
stop = true;
}
} catch (EOFException ee) {
System.out
.println("Got EOFException, close entertainer socket.");
try {
entertainersock.close();
entertainersock = null;
stop = true;
} catch (Exception ex) {

相關文章