下面是一个使用 Jython线程的例子。这个例子显示了一组生产者(producer)和消费者(consumer)线程,它们共享对一个公共缓冲区的访问。我们首先定义这个共享缓冲区,如下所示:
- """ 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线程的示例。
【编辑推荐】