Jython線程示例:定義共享緩沖區(qū)
作者:佚名
本文通過一個實例講解了如何使用Jython線程。這個例子顯示了一組生產(chǎn)者(producer)和消費(fèi)者(consumer)線程,它們共享對一個公共緩沖區(qū)的訪問。
下面是一個使用 Jython線程的例子。這個例子顯示了一組生產(chǎn)者(producer)和消費(fèi)者(consumer)線程,它們共享對一個公共緩沖區(qū)的訪問。我們首先定義這個共享緩沖區(qū),如下所示:
- """ Jython線程示例 """
- from java import lang
- from synchronize import *
- from thread import start_new_thread
- from sys import stdout
- def __waitForSignal (monitor):
- apply_synchronized(monitor, lang.Object.wait, (monitor,))
- def __signal (monitor):
- apply_synchronized(monitor, lang.Object.notifyAll, (monitor,))
- def __xprint (stream, msg):
- print >>stream, msg
- def xprint (msg, stream=stdout):
- """ Synchronized print. """
- apply_synchronized(stream, __xprint, (stream, msg))
- class Buffer:
- """ A thread-safe buffer. """
- def __init__ (self, limit=-1):
- self.__limit = limit # the max size of the buffer
- self.__data = []
- self.__added = () # used to signal data added
- self.__removed = () # used to signal data removed
- def __str__ (self):
- return "Buffer(%s,%i)" % (self.__data, self.__limit)
- def __len__ (self):
- return len(self.__data)
- def add (self, item):
- """ 添加項目。滿的時候等待。 """
- if self.__limit >= 0:
- while len(self.__data) > self.__limit:
- __waitForSignal(self.__removed)
- self.__data.append(item);
- xprint("Added: %s" % item)
- __signal(self.__added)
- def __get (self):
- item = self.__data.pop(0)
- __signal(self.__removed)
- return item
- def get (self, wait=1):
- """ Remove an item. Wait if empty. """
- item = None
- if wait:
- while len(self.__data) == 0:
- __waitForSignal(self.__added)
- item = self.__get()
- else:
- if len(self.__data) > 0: item = self.__get()
- xprint("Removed: %s" % item)
- return item
- get = make_synchronized(get)
以上就是一個Jython線程的示例。
【編輯推薦】
責(zé)任編輯:yangsai
來源:
網(wǎng)絡(luò)轉(zhuǎn)載