2014年1月31日 星期五

How to get the location of an executing JAR file


#-*- coding: utf-8 -*-
System.out.println("0: " + JarLocation.class.getProtectionDomain().getCodeSource().getLocation().getFile());
        System.out.println("1: " + new File(JarLocation.class.getProtectionDomain().getCodeSource().getLocation().getFile()).getCanonicalPath());
        System.out.println("2: " + JarLocation.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        System.out.println("3: " + JarLocation.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        System.out.println("4: " + new File(JarLocation.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getCanonicalPath());
        System.out.println("5: " + JarLocation.class.getClassLoader().getResource("").getPath());
        System.out.println("6: " + new File(JarLocation.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile());
        System.out.println("7: " + JarLocation.class.getProtectionDomain().getCodeSource().getLocation().toString());
        System.out.println("8 :" + System.getProperty("java.class.path"));
        System.out.println("9 :" + new File(System.getProperty("java.class.path")).toURI().getPath());
        System.out.println("10 :"+ new File(System.getProperty("java.class.path")).toURI());
        System.out.println("11:" + new File(".").getAbsolutePath());
        System.out.println("12:" + new File(System.class.getResource("/").getPath()).getCanonicalPath());
        System.out.println("13:" + new File(System.class.getResource("/").toURI().getPath()));
        System.out.println("14:" + System.getProperty("user.dir"));



 執行結果:
D:\Temp>java -jar "JarLocation   space\JarLocation_package.jar"
0: ./
1: D:\Temp
2: ./
3: null
4: D:\Temp
5:
6: null
7: rsrc:./
8 :JarLocation   space\JarLocation_package.jar
9 :/D:/Temp/JarLocation   space/JarLocation_package.jar
10 :file:/D:/Temp/JarLocation%20%20%20space/JarLocation_package.jar
11:D:\Temp\.
12:D:\Temp\JarLocation%20%20%20space
13:D:\Temp\JarLocation   space
14:D:\Temp

D:\Temp>java -jar "JarLocation   space\JarLocation_extract.jar"
0: /D:/Temp/JarLocation%20%20%20space/JarLocation_extract.jar
1: D:\Temp\JarLocation%20%20%20space\JarLocation_extract.jar
2: /D:/Temp/JarLocation%20%20%20space/JarLocation_extract.jar
3: /D:/Temp/JarLocation   space/JarLocation_extract.jar
4: D:\Temp\JarLocation%20%20%20space\JarLocation_extract.jar
5: /D:/Temp/JarLocation%20%20%20space/
6: D:\Temp\JarLocation%20%20%20space
7: file:/D:/Temp/JarLocation%20%20%20space/JarLocation_extract.jar
8 :JarLocation   space\JarLocation_extract.jar
9 :/D:/Temp/JarLocation   space/JarLocation_extract.jar
10 :file:/D:/Temp/JarLocation%20%20%20space/JarLocation_extract.jar
11:D:\Temp\.
12:D:\Temp\JarLocation%20%20%20space
13:D:\Temp\JarLocation   space
14:D:\Temp 

2010年1月28日 星期四

skin


crawl當動詞主要是"爬行"的意思,
但是用在皮膚就是"讓人起雞皮疙瘩"的意思,
什麼時候會起雞皮疙瘩呢?當然就是覺得害怕或噁心囉......

make sb's skin craw
=> to make sb feel afraid or full of disgust

Her singing makes my skin crawl.

2010年1月14日 星期四

歐巴馬給女兒的信》我們一家的大冒險

 
歐巴馬給女兒的信》我們一家的大冒險(中英對照)(原文連結)

原文翻譯得很好,
但為了不要養成依賴中文的習慣,
所以這邊就把翻譯拿掉,
並加入了很多筆記。

這是一篇很好的教材,
尤其對於我這種懶得背單字的傢伙。
(寫給小孩子的會用多難的單字呢??)

“What I Want For You- And Every Child in America”
by President-Elect Barack Obama (Published in Parade Magazine)


Dear Malia and Sasha,

I know that you've both had a lot of fun these last two years on the campaign trail, going to picnics and parades and state fairs, eating all sorts of junk food your mother and I probably shouldn't have let you have. But I also know that it hasn't always been easy for you and Mom, and that as excited as you both are about that new puppy, it doesn't make up for all the time we've been apart. I know how much I've missed these past two years, and today I want to tell you a little more about why I decided to take our family on this journey.

[My notes]
campaign
cam·paign /kæmˈpeɪn/ n [C]
a series of actions intended to achieve a particular result relating to politics or business, or a social improvement
中文的解釋就是:為了達到某一種特別的結果所做的一連串行動,例如政治,商業,或者是社會進步,所以這邊可以翻為競選(活動)

trail
trail1 /treɪl/ n
all the places that a particular group of people visit for a particular purpose
trail 有很多解釋,這邊取其中一個名詞解釋:一個團體為了某一個特別的目的,所去拜訪的所有地方。

所以就有一個片語產生
campaign/election trail
就是"競選之旅"啦

make up
請注意,是 make up,不是 make-up,
make up 也有很多意思,在這邊的意思是"彌補
彌補什麼呢?可以彌補時間,彌補工作,也可以彌補人際關係喔。

I'm trying to make up the time I lost while I was sick.
Have you made up with Patty yet?

apart
a·part /əˈpɑːt US -ɑːrt/ adv, adj
if people are apart, they are not together in the same place, or not having a relationship with each other
當形容詞用時,如果主詞是人,就表示他們沒有在同一個地點,或者是沒有保有某種關係


When I was a young man, I thought life was all about me—about how I'd make my way in the world, become successful, and get the things I want. But then the two of you came into my world with all your curiosity and mischief and those smiles that never fail to fill my heart and light up my day. And suddenly, all my big plans for myself didn't seem so important anymore. I soon found that the greatest joy in my life was the joy I saw in yours. And I realized that my own life wouldn't count for much unless I was able to ensure that you had every opportunity for happiness and fulfillment in yours. In the end, girls, that's why I ran for President: because of what I want for you and for every child in this nation.

[My notes] 
mischief
mis·chief /ˈmɪstʃɪf/ n
bad behaviour (especially of children) that is annoying but does not cause any serious damage or harm
通常是指小孩子那種淘氣的行為
Those children are always getting into mischief

count
count1  /kaunt/ v
to be important or valuable
count 我們知道常常用做"計數"的意思,但是這裡是表示"重要"。

First impression really do count.
His promises don't count for much.

fulfilment
ful·fil·ment BrE fulfillment AmE /fulˈfɪlmənt/ n [U]
the feeling of being happy and satisfied with your life because you are doing interesting, useful, or important things
這是一種對生命快樂,滿足的感覺,這種感覺來自於你可以從事有趣,有用,或重要的事情,翻成"自我實現"似乎很貼切

run for + (sb/sth)
to be a candidate in an election for a political position, especially in the US
British Equivalent:stand for
在美式英文中,run for 也有"從事競選"的意思

to run for president
to run in the election
Clinton ran a second time in 1996.


I want all our children to go to schools worthy of their potential—schools that challenge them, inspire them, and instill in them a sense of wonder about the world around them. I want them to have the chance to go to college—even if their parents aren't rich. And I want them to get good jobs: jobs that pay well and give them benefits like health care, jobs that let them spend time with their own kids and retire with dignity.

[My notes]
instill
in·stil BrE instill AmE /ɪnˈstɪl/ v
to teach someone to think, behave, or feel in a particular way over a period of time
灌輸 (情感/思想)

instill confidence/fear/discipline to sb


I want us to push the boundaries of discovery so that you'll live to see new technologies and inventions that improve our lives and make our planet cleaner and safer. And I want us to push our own human boundaries to reach beyond the divides of race and region, gender and religion that keep us from seeing the best in each other.

[My notes]
push (back) the boundaries of sth
to make a new discovery, work of art etc that is very different from what people have known before, and that changes the way they think
boundary 是邊界,或界線的意思,把 sth 的邊界推開,就是挑戰 sth 的極限,去發掘已知以外的事物。所以 "to push the boundaries of discovery" 這邊可以翻譯成 "向發現的極限挑戰"。

beyond
be·yond1  /bɪˈjɔnd US -ˈjɑːnd/ prep, adv
on or to the further side of sth
The road continues beyond the village up into the hills.

beyond the divides
divide 當名詞可以指意見或是信念的分歧,造成人與人之間的摩擦。
所以 beyond the divides 就是"跨越人與人之間的藩籬",至於是什麼藩籬呢?
那就是 divides of 後面接的那一大串囉。

keep (sb/sth) from sth
to prevent sb from doing sth or prevent sth from happening

His ex-wife had kept him from seeing his children.
I hope I haven't kept you from your work.
Put the pizza in the bottom of the oven to keep the cheese from burning.
The play was so boring, I could hardly keep myself from falling asleep.


Sometimes we have to send our young men and women into war and other dangerous situations to protect our country—but when we do, I want to make sure that it is only for a very good reason, that we try our best to settle our differences with others peacefully, and that we do everything possible to keep our servicemen and women safe. And I want every child to understand that the blessings these brave Americans fight for are not free—that with the great privilege of being a citizen of this nation comes great responsibility.

[My notes]
only for a very good reason
"師出有名",翻得很好啊。

servicemen
ser·vice·man /ˈsəːvɪsmən US ˈsəːr-/ n plural servicemen /-mən/ [C]
a man who is a member of the military
同理,servicewoman 就不解釋了。


That was the lesson your grandmother tried to teach me when I was your age, reading me the opening lines of the Declaration of Independence and telling me about the men and women who marched for equality because they believed those words put to paper two centuries ago should mean something.

[My notes]
read sb sth
read (sth) to sb
to say the words in a book, newspaper etc so that people can hear them


She helped me understand that America is great not because it is perfect but because it can always be made better—and that the unfinished work of perfecting our union falls to each of us. It's a charge we pass on to our children, coming closer with each new generation to what we know America should be.

[My notes]
It's a charge we pass on to our children, coming closer (with each new generation) to what we know America should be.
pass on to 是"傳遞"的意思,coming 後面接的子句是用來形容 charge。


I hope both of you will take up that work, righting the wrongs that you see and working to give others the chances you've had. Not just because you have an obligation to give something back to this country that has given our family so much—although you do have that obligation. But because you have an obligation to yourself. Because it is only when you hitch your wagon to something larger than yourself that you will realize your true potential.

[My notes]
obligation
ob·li·ga·tion  /ˌɔblɪˈgeɪʃən US ˌɑːb-/ n [U and C]
a moral or legal duty to do sth
道義或法律上的義務

Parents are under a legal obligation to educate their children.

hitch
hitch1 /hɪtʃ/ v
to fasten sth to sth else, using a rope, chain etc
用繩子或鍊子把東西拴住 (在本文中的意思)

She hitched the pony to the gate.

to get a free ride in a person's car; to travel around in this way, by standing at the side of the road and trying to get passing cars to stop
搭便車
hitch across/around/to

The hitched a ride in a truck.
We spent the summer hitching around Europe.
They hitched accross the States.

hitch sth (up)
to pull up a piece of your clothing
把衣物往上拉(推)

She hitched up her skirt and waded into the river.

get hitched
to get married

They got hitched without telling their parents.


These are the things I want for you—to grow up in a world with no limits on your dreams and no achievements beyond your reach, and to grow into compassionate, committed women who will help build that world. And I want every child to have the same chances to learn and dream and grow and thrive that you girls have. That's why I've taken our family on this great adventure.

[My notes]
committed
com·mit·ted /kəˈmɪtɪd/ adj
willing to work hard and  give your time and energy to sth
堅定去做某件事情的

thrive
thrive /θraɪv/ v past tense thrived or throve /θrəuv US θrouv/ past participle thrived [I] formal
to become very successful or very strong and healthy
可以用來形容人,動植物,企業,房地產,城市等等,
所以翻成"茁壯,成功,蓬勃發展"都可以吧!

New businesses thrive in this area.

thrive on sth
to enjoy sth or be successful at sth, especially one that other people find difficult or unpleasant

He thrives on hard work.


I am so proud of both of you. I love you more than you can ever know. And I am grateful every day for your patience, poise, grace, and humor as we prepare to start our new life together in the White House.


Love, Dad

[My notes]
poise
poise1 /pɔɪz/ n [U]
a calm, confident way of behaving, combined with an ability to control your feelings or reactions in difficult situations
鎮定,平衡

She seemed embarrassed for a moment but quickly recovered her poise.

2010年1月13日 星期三

occasion

occasion
oc·ca·sion1  /əˈkeɪʒən/ n

on ... occasion  [C]
a time when something happens
  1. On one occasion, she called me in the middle of the night.
  2. I've seen Jana with them on several occasions.
---

occasion + (for sth / doing sth) [singular]
a suitable or favourable time
  1. This was the occasion for expressions of friendship by the two presidents.
  2. I'll speak to him about it if the occasion arises (= if I get a chance). 
---  
[C]
a special event, ceremony or celebration
  1. They marked the occasion (= celebrated it) with an open-air concert.
--- 
[U] formal
a cause or reason
  1. I had occasion to call on him last year.
--- 
if (the) occasion arises
formal if a particular action ever becomes necessary

  1. I'm willing to go to court over this if the occasion arises (= if it becomes necessary).
--- 
on occasion (=sometimes =once in a while)

sometimes but not often
  1. On occasion prisoners were allowed visits from their families.
  2. Herry doesn't like to socialize, but he does go out on occasion.

------
occasion2 v [T] formal

to cause something
  1. The flight delay was occasioned by the need for a further security check.
--- 
occasion sb sth
  1. Your behaviour has occasioned us a great deal of anxiety.

HINT sense 1
Do not use occasion when you mean 'a time when it is possible for you to do what you want to do'. Use opportunity or chance: Do not waste this opportunity (NOT this occasion).

2010年1月12日 星期二

intention

intention
/ɪnˈtenʃən/ n [U and C]
a plan or desire to do sth.

have/with [no] intention of doing sth
  • He left England with the intention of travelling in Africa.
  • I have no intention of retiring just yet.
intention to do sth
  • It is our intention to be the number one distributor of health products.

如何取得滑鼠座標

標題只是個晃子,
主要是要測試 http://tohtml.com/
效果好像真的不錯優~

#!/usr/bin/python
# -*- coding: utf-8 -*-

import win32gui
import time

while (True):
    x,y = win32gui.GetCursorPos()
    time.sleep(0.2)
    print x,y

2010年1月7日 星期四

Threading in Python

 
對現今的應用程式來說,
multi-thread 是不可或缺的部份。
那麼在 python 中要怎麼 implement multi-thread 呢?

這裡介紹兩個 python 所提供的 module -- thread and threading

thread module


使用 thread module 很像在 win32 的 CreateThread,
只是 CreateThread 換成了 thread.start_new_thread(function, args[, kwargs])
第一個參數就是 thread function,第二個參數是我們要傳進去的資料(tuples),
我們看一個簡單的例子:

#-*- coding: utf-8 -*-
#!/usr/bin/python

import thread
import time

def Threadfun(string, sleeptime, *args):
    while(True):
        print '{0}_{1}\n'.format(string, sleeptime)
        time.sleep(sleeptime)

if __name__ == "__main__":
    for i in range(1,5):
        thread.start_new_thread(Threadfun, ("ThreadFun", i))
    while(True):
        print 'MainThread {0}'.format(thread.get_ident())
        time.sleep(1)


以上就是很基本的建立多個執行緒的方法。

如果需要同步呢?
我們可以用 Lock Object。
Lock Object 可以藉由呼叫 allocate_lock() 得到。
先看看沒有同步會是什麼情況。

#-*- coding: utf-8 -*-
#!/usr/bin/python

import thread
import time

def Threadfun(string, sleeptime, lock, *args):
    while(True):
        print 'Enter_{0}\r\n'.format(string)
        time.sleep(sleeptime)
        print 'Leave_{0}\r\n'.format(string)

if __name__ == "__main__":
    lock = thread.allocate_lock()
    thread.start_new_thread(Threadfun, ("ThreadFun1", 2, lock))
    thread.start_new_thread(Threadfun, ("ThreadFun2", 2, lock))

    while (True):
        pass


執行的結果如下:













看出來了嗎?一個都還沒離開,另一個就進去了。

使用 Lock Object 來保護:
#-*- coding: utf-8 -*-
#!/usr/bin/python

import thread
import time

def Threadfun(string, sleeptime, lock, *args):
    while(True):
        lock.acquire()
        print 'Enter_{0}\r\n'.format(string)
        time.sleep(sleeptime)
        print 'Leave_{0}\r\n'.format(string)
        lock.release()

if __name__ == "__main__":
    lock = thread.allocate_lock()
    thread.start_new_thread(Threadfun, ("ThreadFun1", 2, lock))
    thread.start_new_thread(Threadfun, ("ThreadFun2", 2, lock))

    while (True):
        pass


執行結果如下:













這樣才是我們要的結果喔!
p.s. 根據 python 官方文件,thread module在 python 3.0 已經改為 __thread
可是還是建議使用高階的 threading module

threading module

threading module 裡面包含了以下 components
  • Lock object
  • RLock object
  • Semaphore Object
  • Condition Object
  • Event Object
  • Thread Object
threading.Thread

Thread Object wrapper 了 start_new_thread() 這個 function。

當我們呼叫 start() 時,就會自動去呼叫 run() ,
所以我們只能夠 override __init()__ 以及 run() 這兩個 method,
絕對不可以 override start()。

#-*- coding: utf-8 -*-
#!/usr/bin/python

from threading import Thread
import time

class MyThread(Thread):
    def __init__(self, string, sleeptime):
        Thread.__init__(self)
        self.sleeptime = sleeptime
        self.setName(str(sleeptime))
    def run(self):
        while(True):
            print 'Threadfun_{0}\r\n'.format(self.getName())
            time.sleep(self.sleeptime)
if __name__ == "__main__":
    thrList = [MyThread('ThreadFun', i) for i in range(1,5)]

    # thrList[0]~thrList[3]
    for i in range(0,4):
        thrList[i].start()
    # another way
    #for i in range(1,5):
    #    MyThread('ThreadFun', i).start()


另外一種作法是把 thread function 當參數,在建構物件時傳入,
那麼一樣在呼叫 start() 是,這個函式就會被執行。

threading.Condition

Condition 也是一種鎖,
也就是說它也提供 acquire/release 方法。
除此之外,
它還可以wait/notify/notifyAll,
但是要注意的一點是,
wait/notify/notifyAll 一定要跟 acquire/release 一起使用,
否則就會拋出 RuntimeError 異常。

我們可以用一個簡單的 productor/consumer 模型來當作範例。
#!/usr/bin/python
# -*- coding:utf-8 -*-

from threading import *
import time

class itemX:
    def __init__(self):
        self.cnt = 0

    def produce(self, num=1):
        self.cnt += 1

    def consume(self, num=1):
        if self.cnt:
            self.cnt -= 1
        else:
            print 'WARNING***********************WARNING'

    def isEmpty(self):
        return not self.cnt

    def getCount(self):
        return self.cnt

class Producer(Thread):
    def __init__(self, condition, item, sleeptime=2):
        Thread.__init__(self)
        self.con = condition
        self.item = item
        self.sleeptime = sleeptime

    def run(self):
        while (True):
            time.sleep(self.sleeptime)
            self.con.acquire()
            self.item.produce()
            print 'produce 1 product\r\n'
            print self.item.getCount()
            self.con.notifyAll()
            self.con.release()

class Consumer(Thread):
    def __init__(self, condition, item, sleeptime=2):
        Thread.__init__(self)
        self.con = condition
        self.item = item
        self.sleeptime = sleeptime
    def run(self):
        while (True):
            time.sleep(self.sleeptime)
            self.con.acquire()
            print '({0})enter'.format(self.getName())
            while self.item.isEmpty():
                print '({0})wait'.format(self.getName())
                self.con.wait()
            self.item.consume()
            print '({0})consume 1 product\r\n'.format(self.getName())
            print self.item.getCount()
            self.con.release()


if __name__ == "__main__":
    X = itemX()
    cond = Condition()
    Producer(cond, X).start()
    Consumer(cond, X).start()
    Consumer(cond, X).start()

    while (True):
        pass

threading.Event

event 是很常用的同步機制,
我們先用 event 改寫上一個例子,
再來討論它有什麼要注意的地方。

#!/usr/bin/python
# -*- coding:utf-8 -*-

from threading import *
import time

class itemX:
    def __init__(self):
        self.cnt = 0

    def produce(self, num=1):
        self.cnt += 1

    def consume(self, num=1):
        if self.cnt:
            self.cnt -= 1
        else:
            print 'WARNING***********************WARNING'

    def isEmpty(self):
        return not self.cnt

    def getCount(self):
        return self.cnt

class Producer(Thread):
    def __init__(self, condition, event, item, sleeptime=1):
        Thread.__init__(self)
        self.con = condition
        self.event = event
        self.item = item
        self.sleeptime = sleeptime

    def run(self):
        while (True):
            time.sleep(self.sleeptime)
            self.con.acquire()
            self.item.produce()
            print 'produce 1 product, remain({0})\r\n'.format(self.item.getCount())
            self.event.set()
            self.con.release()

class Consumer(Thread):
    def __init__(self, condition, event, item, sleeptime=1):
        Thread.__init__(self)
        self.con = condition
        self.event = event
        self.item = item
        self.sleeptime = sleeptime
    def run(self):
        while (True):
            time.sleep(self.sleeptime)
            self.con.acquire()
            print '({0})enter\r\n'.format(self.getName())
            #while self.item.isEmpty():
            while (True):
                print '({0})wait'.format(self.getName())
                self.event.wait()
                break
            self.item.consume()
            self.event.clear()
            print '({0})consume 1 product, remain({1})\r\n'.format(self.getName(), self.item.getCount())
            self.con.release()


if __name__ == "__main__":
    X = itemX()
    cond_Con = Condition()
    cond_Pro = Condition()
    event = Event()
    Producer(cond_Pro, event, X).start()
    Consumer(cond_Con, event, X).start()
    Consumer(cond_Con, event, X).start()

    while (True):
        pass


首先,
event 的 block 機制跟 condition 是很不一樣的,
對condition來說,notify 是一個通知,
有人在等,通知才有意義,
如果沒有人等,通知是沒有意義的。
notify 和 wait 是有序的,
就是說,假設通知先發生了,
這時候才有人開始等,
那麼是絕對等不到已經發生的那一個通知。

可是 event 不一樣,event 是一種狀態。
當 event 被設定了,
它就處於激發狀態,
只要狀態沒有改變,
任何時候都可以等得到。

為了強迫 consumer 一定要等到 event 才能 consume,
我們把上一個範例的 "while self.item.isEmpty():" 改成 "while (True):"
當然 Lock(Critical Section) 的保護也是必要的,
才不會發生多個 consumers 同時 consume 的情況(race condition)。

producer 的 Lock 在這個範例可以不要,
但如果有多個 producers 就一定要加,
特別要注意的一點是,
producer 用的 Lock 和 consumer 的必須要不一樣,
不然會出現 deadlock。

還有就是這邊的 event 是 manual reset,
也就是激發後必須手動呼叫 clear() 方法使其回到未激發狀態。

threading.Timer
Timer 也是 threading 的一個元件,
可以在指定的時間間隔後,執行某一個動作(函式),
例如:

#-*- coding: utf-8 -*-
#!/usr/bin/python

from threading import Time

def hello(msg):
    print msg

t = Timer(3, hello, ['Hello world'])
t.start()


Pooling Threads

最後想要討論一個有趣的東西。
不同的作業系統對可執行的 thread 限制都不一樣,
有時候我們擔心一次建立太多 thread 會造成系統(或程式)效能變差,
比如說我們只想建立兩個 threads,可是我們有十件工作要做,
那麼我們就可以用排程的概念來實做。

在程式的一開始先把兩個 thread 建好 (thread pool),
然後利用 python 的 Queue module,
把十件工作的資料都 put 進 Queue。
在 thread function 裡面會去 get Queue 的資料,
只要 get 到,thread 就會開始工作。

#!/usr/bin/python
#-*- coding:utf-8 -*-

from threading import *
import Queue
import time

class MyThread(Thread):
    def __init__(self, condition):
        Thread.__init__(self)
        self.cond = condition

    def run(self):
        print '{0} start\r\n'.format(self.getName())
        global cnt
        while (True):
            id = threadPool.get()
            if id != None:
            self.cond.acquire()
            print '{0}_{1}'.format(self.getName(), id)
            for x in xrange(101):
               cnt += x
               time.sleep(2)
            print 'cnt = {0}\r\n'.format(cnt)
            cnt = 0
            self.cond.release()
            threadPool.task_done()


threadPool = Queue.Queue(0)
condition = Condition()
cnt = 0
for i in xrange(2):
    MyThread(condition).start()

for i in xrange(10):
    threadPool.put(i)

threadPool.join()
print 'done'


在 thread function 最後呼叫 task_done() 是為了讓 Queue 知道這一個工作已經完成,
是給 Queue.join() 作為參考。

如果這些工作會存取到相同的資源,
還是記得要用 Lock 保護。

Queue module 是 thread safe,所以這樣的應用是沒有問題的。