public class Sync {
public synchronized void execute(String funcName) {
System.out.println(funcName)
}
}
public synchronized void execute(String funcName) {
System.out.println(funcName)
}
}
Python 範例如下:
import time
import threading from threading
import Thread
# 實作 synchronized
def synchronized(func):
func.__lock__ = threading.Lock()
def synced_func(*args, **kws):
with func.__lock__:
return func(*args, **kws)
return synced_func
import threading from threading
import Thread
# 實作 synchronized
def synchronized(func):
func.__lock__ = threading.Lock()
def synced_func(*args, **kws):
with func.__lock__:
return func(*args, **kws)
return synced_func
synchronized 使用方式:
# 需要執行synchronized的函數
@synchronized
def execute(func_name):
print func_name
time.sleep(2)
@synchronized
def execute(func_name):
print func_name
time.sleep(2)
Reference:
[1] Synchronized in Python
沒有留言:
張貼留言