Skip to content

Instantly share code, notes, and snippets.

# Method-1
class Foo(object):
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, val):
self._x = val
import Queue
q = Queue.PriorityQueue()
q.put((2, 1, 'Orange'))
q.put((1, 3, 'Tomato'))
q.put((1, 2, 'Banana'))
q.put((2, 1, 'Apple'))
while not q.empty():
item = q.get()
import Queue, thread
def worker(q):
while True:
i = q.get()
print('Task %s done.' % i)
q.task_done()
q = Queue.Queue()
@ericzhong
ericzhong / thread.py
Last active May 24, 2017 13:14
多线程
import thread, sys
def print_char(c):
for i in range(100):
print c, # or sys.stdout.write()
sys.stdout.flush()
thread.start_new_thread(print_char, ('0',))
thread.start_new_thread(print_char, ('1',))
import threading
class Worker(threading.Thread):
def __init__(self, id, ch):
super(Worker, self).__init__()
self.id = id
self.ch = ch
def run(self):
print "Start worker %s." % self.id
from greenlet import greenlet
def test1():
print 1
g2.switch()
print 2
def test2():
print 3
g1.switch()
import eventlet
from eventlet.green import urllib2
urls = [
"http://news.baidu.com/",
"https://zhidao.baidu.com/",
"http://image.baidu.com/",
]
def fetch(url):
@ericzhong
ericzhong / tls.py
Last active May 25, 2017 08:59
线程局部存储
import threading, time
tls = threading.local()
def say_hi():
name = threading.current_thread().name
if hasattr(tls, 'init'):
print("%s: Welcome back." % name)
else:
class ListMetaClass(type):
def __new__(cls, name, bases, attrs):
attrs['times'] = lambda self, n: self*n
return type.__new__(cls, name, bases, attrs)
class MyList(list, metaclass=ListMetaClass):
pass
l = MyList([1,2,3])
print(l.times(2))
@ericzhong
ericzhong / MultiThread.java
Last active May 27, 2017 03:02
多线程
import java.util.Random;
class PrintChar implements Runnable {
private String ch;
PrintChar(String str) {
this.ch=str.substring(0,1);
}
public void run() {