我必須在Python 2.7中編寫一個類,並且我有一些問題。 我來自一個Java的背景,得知蟒蛇最近相當Python的等效Java的函數wait(),notify(),同步
這裏是什麼,如果我必須用Java做我會寫
public class CommandSender extends Thread {
private boolean isTimeOut;
private boolean running;
private ArrayList<Command> waitingList;
public CommandSender() {
running = false;
waitingList = new LinkedList<Command>();
isTimeOut = false;
}
public void run() {
running = true;
while (running) {
synchronized (this) {
while (waitingList.isEmpty() && running) {
try {
wait();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
while (!waitingList.isEmpty() && running) {
currentCmd = waitingList.remove(0);
// doSomething(currentCmd)
}
}
}
}
public synchronized void sendCommand(Command cmd) {
waitingList.add(cmd);
notify();
}
public synchronized boolean isTimeOut() {
return isTimeOut;
}
}
我有什麼一時
class CommandSender(threading.Thread)
def __init__(self):
threading.Thread.__init__(self)
self.waiting_list = []
self.running = False
self.is-time_out = False
self.my_lock = threading.Lock()
def run(self):
self.running = True
with self.my_lock:
while len(self.waiting_list) == 0 and self.running:
# Don't know what I have to do here
while len(self.waiting_list) != 0 and self.running:
# Do my stuff
def send_command(self, cmd):
with self.my_lock:
self.waiting_list.append(cmd)
# Notify ?
def is_time_out(self):
with self.my_lock:
return self.is_rime_out
做我使用的每個實例都有一個鎖,因爲有CommandSender
只有一個實例那麼怎麼辦等待/通知過程?我的同步塊是否很好用?
謝謝!
一個側面說明:我個人認爲這是一個更好的模式來使用鎖定對象(無論語言),而不是同步整個對象。否則,如果您的對象用於外部同步,將導致奇怪的結果。 – Krumelur